1. 程式人生 > 程式設計 >Golang實現http server提供壓縮檔案下載功能

Golang實現http server提供壓縮檔案下載功能

最近遇到了一個下載靜態html報表的需求,需要以提供壓縮包的形式完成下載功能,實現的過程中發現相關文件非常雜,故總結一下自己的實現。

開發環境:

系統環境:MacOS + Chrome
框架:beego
壓縮功能:tar + gzip
目標壓縮檔案:自帶資料和全部包的靜態html檔案

首先先提一下http server檔案下載的實現,其實就是在後端返回前端的資料包中,將資料頭設定為下載檔案的格式,這樣前端收到返回的響應時,會直接觸發下載功能(就像時平時我們在chrome中點選下載那樣)
資料頭設定格式如下:

func (c *Controller)Download() {
  //...檔案資訊的產生邏輯
  //
  //rw為responseWriter
  rw := c.Ctx.ResponseWriter
  //規定下載後的檔名
  rw.Header().Set("Content-Disposition","attachment; filename="+"(檔名字)")
  rw.Header().Set("Content-Description","File Transfer")
  //標明傳輸檔案型別
  //如果是其他型別,請參照:https://www.runoob.com/http/http-content-type.html
  rw.Header().Set("Content-Type","application/octet-stream")
  rw.Header().Set("Content-Transfer-Encoding","binary")
  rw.Header().Set("Expires","0")
  rw.Header().Set("Cache-Control","must-revalidate")
  rw.Header().Set("Pragma","public")
  rw.WriteHeader(http.StatusOK)
  //檔案的傳輸是用byte slice型別,本例子中:b是一個bytes.Buffer,則需呼叫b.Bytes()
  http.ServeContent(rw,c.Ctx.Request,"(檔名字)",time.Now(),bytes.NewReader(b.Bytes()))
}

這樣,beego後端就會將在頭部標記為下載檔案的資料包傳送給前端,前端收到後會自動啟動下載功能。

然而這只是最後一步的情況,如何將我們的檔案先進行壓縮再發送給前端提供下載呢?

如果需要下載的不只一個檔案,需要用tar打包,再用gzip進行壓縮,實現如下:

  //最內層用bytes.Buffer來進行檔案的儲存
  var b bytes.Buffer
  //巢狀tar包的writter和gzip包的writer
  gw := gzip.NewWriter(&b)
  tw := tar.NewWriter(gw)


  dataFile := //...檔案的產生邏輯,dataFile為File型別
  info,_ := dataFile.Stat()
  header,_ := tar.FileInfoHeader(info,"")
  //下載後當前檔案的路徑設定
  header.Name = "report" + "/" + header.Name
  err := tw.WriteHeader(header)
  if err != nil {
    utils.LogErrorln(err.Error())
    return
  }
  _,err = io.Copy(tw,dataFile)
  if err != nil {
    utils.LogErrorln(err.Error())
  }
  //...可以繼續新增檔案
  //tar writer 和 gzip writer的關閉順序一定不能反
  tw.Close()
  gw.Close()

最後和中間步驟完成了,我們只剩File檔案的產生邏輯了,由於是靜態html檔案,我們需要把所有html引用的依賴包全部完整的寫入到生成的檔案中的<script>和<style>標籤下。此外,在本例子中,報告部分還需要一些靜態的json資料來填充表格和影象,這部分資料是以map儲存在記憶體中的。當然可以先儲存成檔案再進行上面一步的打包壓縮,但是這樣會產生併發的問題,因此我們需要先將所有的依賴包檔案和資料寫入一個byte.Buffer中,最後將這個byte.Buffer轉回File格式。

Golang中並沒有寫好的byte.Buffer轉檔案的函式可以用,於是我們需要自己實現。

實現如下:

type myFileInfo struct {
  name string
  data []byte
}

func (mif myFileInfo) Name() string    { return mif.name }
func (mif myFileInfo) Size() int64    { return int64(len(mif.data)) }
func (mif myFileInfo) Mode() os.FileMode { return 0444 }    // Read for all
func (mif myFileInfo) ModTime() time.Time { return time.Time{} } // Return whatever you want
func (mif myFileInfo) IsDir() bool    { return false }
func (mif myFileInfo) Sys() interface{}  { return nil }

type MyFile struct {
  *bytes.Reader
  mif myFileInfo
}

func (mf *MyFile) Close() error { return nil } // Noop,nothing to do

func (mf *MyFile) Readdir(count int) ([]os.FileInfo,error) {
  return nil,nil // We are not a directory but a single file
}

func (mf *MyFile) Stat() (os.FileInfo,error) {
  return mf.mif,nil
}

依賴包和資料的寫入邏輯:

func testWrite(data map[string]interface{},taskId string) http.File {
  //最後生成的html,開啟html模版
  tempfileP,_ := os.Open("views/traffic/generatePage.html")
  info,_ := tempfileP.Stat()
  html := make([]byte,info.Size())
  _,err := tempfileP.Read(html)
  // 將data資料寫入html
  var b bytes.Buffer
  // 建立Json編碼器
  encoder := json.NewEncoder(&b)

  err = encoder.Encode(data)
  if err != nil {
    utils.LogErrorln(err.Error())
  }
  
  // 將json資料新增到html模版中
  // 方式為在html模版中插入一個特殊的替換欄位,本例中為{Data_Json_Source}
  html = bytes.Replace(html,[]byte("{Data_Json_Source}"),b.Bytes(),1)

  // 將靜態檔案新增進html
  // 如果是.css,則前後增加<style></style>標籤
  // 如果是.js,則前後增加<script><script>標籤
  allStaticFiles := make([][]byte,0)
  // jquery 需要最先進行新增
  tempfilename := "static/report/jquery.min.js"

  tempfileP,_ = os.Open(tempfilename)
  info,_ = os.Stat(tempfilename)
  curFileByte := make([]byte,err = tempfileP.Read(curFileByte)

  allStaticFiles = append(allStaticFiles,[]byte("<script>"))
  allStaticFiles = append(allStaticFiles,curFileByte)
  allStaticFiles = append(allStaticFiles,[]byte("</script>"))
  //剩下的所有靜態檔案
  staticFiles,_ := ioutil.ReadDir("static/report/")
  for _,tempfile := range staticFiles {
    if tempfile.Name() == "jquery.min.js" {
      continue
    }
    tempfilename := "static/report/" + tempfile.Name()

    tempfileP,_ := os.Open(tempfilename)
    info,_ := os.Stat(tempfilename)
    curFileByte := make([]byte,info.Size())
    _,err := tempfileP.Read(curFileByte)
    if err != nil {
      utils.LogErrorln(err.Error())
    }
    if isJs,_ := regexp.MatchString(`\.js$`,tempfilename); isJs {
      allStaticFiles = append(allStaticFiles,[]byte("<script>"))
      allStaticFiles = append(allStaticFiles,curFileByte)
      allStaticFiles = append(allStaticFiles,[]byte("</script>"))
    } else if isCss,_ := regexp.MatchString(`\.css$`,tempfilename); isCss {
      allStaticFiles = append(allStaticFiles,[]byte("<style>"))
      allStaticFiles = append(allStaticFiles,[]byte("</style>"))
    }
    tempfileP.Close()
  }
  
  // 轉成http.File格式進行返回
  mf := &MyFile{
    Reader: bytes.NewReader(html),mif: myFileInfo{
      name: "report.html",data: html,},}
  var f http.File = mf
  return f
}

OK! 目前為止,後端的檔案生成->打包->壓縮都已經做好啦,我們把他們串起來:

func (c *Controller)Download() {
  var b bytes.Buffer
  gw := gzip.NewWriter(&b)

  tw := tar.NewWriter(gw)

  // 生成動態report,並新增進壓縮包
  // 呼叫上文中的testWrite方法
  dataFile := testWrite(responseByRules,strTaskId)
  info,"")
  header.Name = "report_" + strTaskId + "/" + header.Name
  err := tw.WriteHeader(header)
  if err != nil {
    utils.LogErrorln(err.Error())
    return
  }
  _,dataFile)
  if err != nil {
    utils.LogErrorln(err.Error())
  }

  tw.Close()
  gw.Close()
  rw := c.Ctx.ResponseWriter
  rw.Header().Set("Content-Disposition","attachment; filename="+"report_"+strTaskId+".tar.gz")
  rw.Header().Set("Content-Description","File Transfer")
  rw.Header().Set("Content-Type","public")
  rw.WriteHeader(http.StatusOK)
  http.ServeContent(rw,"report_"+strTaskId+".tar.gz",bytes.NewReader(b.Bytes()))
}

後端部分已經全部實現了,前端部分如何接收呢,本例中我做了一個按鈕巢狀<a>標籤來進行請求:

<a href="/traffic/download_indicator?task_id={{$.taskId}}&task_type={{$.taskType}}&status={{$.status}}&agent_addr={{$.agentAddr}}&glaucus_addr={{$.glaucusAddr}}" rel="external nofollow" >
   <button style="font-family: 'SimHei';font-size: 14px;font-weight: bold;color: #0d6aad;text-decoration: underline;margin-left: 40px;" type="button" class="btn btn-link">下載報表</button>
</a>

這樣,當前端頁面中點選下載報表按鈕之後,會自動啟動下載,下載我們後端傳回的report.tar.gz檔案。

到此這篇關於Golang實現http server提供壓縮檔案下載功能的文章就介紹到這了,更多相關Golang http server 壓縮下載內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!