欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Golang實現(xiàn)http server提供壓縮文件下載功能

 更新時間:2021年01月07日 14:16:07   作者:Hoofffman  
這篇文章主要介紹了Golang實現(xiàn)http server提供壓縮文件下載功能,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

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

開發(fā)環(huán)境:

系統(tǒng)環(huán)境:MacOS + Chrome
框架:beego
壓縮功能:tar + gzip
目標壓縮文件:自帶數(shù)據(jù)和全部包的靜態(tài)html文件

首先先提一下http server文件下載的實現(xiàn),其實就是在后端返回前端的數(shù)據(jù)包中,將數(shù)據(jù)頭設置為下載文件的格式,這樣前端收到返回的響應時,會直接觸發(fā)下載功能(就像時平時我們在chrome中點擊下載那樣)
數(shù)據(jù)頭設置格式如下:

func (c *Controller)Download() {
  //...文件信息的產(chǎn)生邏輯
  //
  //rw為responseWriter
  rw := c.Ctx.ResponseWriter
  //規(guī)定下載后的文件名
  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,則需調(diào)用b.Bytes()
  http.ServeContent(rw, c.Ctx.Request, "(文件名字)", time.Now(), bytes.NewReader(b.Bytes()))
}

這樣,beego后端就會將在頭部標記為下載文件的數(shù)據(jù)包發(fā)送給前端,前端收到后會自動啟動下載功能。

然而這只是最后一步的情況,如何將我們的文件先進行壓縮再發(fā)送給前端提供下載呢?

如果需要下載的不只一個文件,需要用tar打包,再用gzip進行壓縮,實現(xiàn)如下:

  //最內(nèi)層用bytes.Buffer來進行文件的存儲
  var b bytes.Buffer
  //嵌套tar包的writter和gzip包的writer
  gw := gzip.NewWriter(&b)
  tw := tar.NewWriter(gw)


  dataFile := //...文件的產(chǎn)生邏輯,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())
  }
  //...可以繼續(xù)添加文件
  //tar writer 和 gzip writer的關閉順序一定不能反
  tw.Close()
  gw.Close()

最后和中間步驟完成了,我們只剩File文件的產(chǎn)生邏輯了,由于是靜態(tài)html文件,我們需要把所有html引用的依賴包全部完整的寫入到生成的文件中的<script>和<style>標簽下。此外,在本例子中,報告部分還需要一些靜態(tài)的json數(shù)據(jù)來填充表格和圖像,這部分數(shù)據(jù)是以map存儲在內(nèi)存中的。當然可以先保存成文件再進行上面一步的打包壓縮,但是這樣會產(chǎn)生并發(fā)的問題,因此我們需要先將所有的依賴包文件和數(shù)據(jù)寫入一個byte.Buffer中,最后將這個byte.Buffer轉(zhuǎn)回File格式。

Golang中并沒有寫好的byte.Buffer轉(zhuǎn)文件的函數(shù)可以用,于是我們需要自己實現(xiàn)。

實現(xiàn)如下:

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
}

依賴包和數(shù)據(jù)的寫入邏輯:

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數(shù)據(jù)寫入html
  var b bytes.Buffer
  // 創(chuàng)建Json編碼器
  encoder := json.NewEncoder(&b)

  err = encoder.Encode(data)
  if err != nil {
    utils.LogErrorln(err.Error())
  }
  
  // 將json數(shù)據(jù)添加到html模版中
  // 方式為在html模版中插入一個特殊的替換字段,本例中為{Data_Json_Source}
  html = bytes.Replace(html, []byte("{Data_Json_Source}"), b.Bytes(), 1)

  // 將靜態(tài)文件添加進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, info.Size())
  _, err = tempfileP.Read(curFileByte)

  allStaticFiles = append(allStaticFiles, []byte("<script>"))
  allStaticFiles = append(allStaticFiles, curFileByte)
  allStaticFiles = append(allStaticFiles, []byte("</script>"))
  //剩下的所有靜態(tài)文件
  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, curFileByte)
      allStaticFiles = append(allStaticFiles, []byte("</style>"))
    }
    tempfileP.Close()
  }
  
  // 轉(zhuǎn)成http.File格式進行返回
  mf := &MyFile{
    Reader: bytes.NewReader(html),
    mif: myFileInfo{
      name: "report.html",
      data: html,
    },
  }
  var f http.File = mf
  return f
}

OK! 目前為止,后端的文件生成->打包->壓縮都已經(jīng)做好啦,我們把他們串起來:

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

  tw := tar.NewWriter(gw)

  // 生成動態(tài)report,并添加進壓縮包
  // 調(diào)用上文中的testWrite方法
  dataFile := testWrite(responseByRules, strTaskId)
  info, _ := dataFile.Stat()
  header, _ := tar.FileInfoHeader(info, "")
  header.Name = "report_" + strTaskId + "/" + 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())
  }

  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", "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)
  http.ServeContent(rw, c.Ctx.Request, "report_"+strTaskId+".tar.gz", time.Now(), bytes.NewReader(b.Bytes()))
}

后端部分已經(jīng)全部實現(xiàn)了,前端部分如何接收呢,本例中我做了一個按鈕嵌套<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實現(xiàn)http server提供壓縮文件下載功能的文章就介紹到這了,更多相關Golang http server 壓縮下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 詳解簡單高效的Go?struct優(yōu)化

    詳解簡單高效的Go?struct優(yōu)化

    這篇文章主要為大家介紹了簡單高效的Go?struct優(yōu)化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • Go語言讀取文件的方法小結

    Go語言讀取文件的方法小結

    寫程序時經(jīng)常需要從一個文件讀取數(shù)據(jù),然后輸出到另一個文件,這篇文章主要為大家詳細介紹了Go語言讀取文件的幾種方法,希望對大家有所幫助
    2024-01-01
  • Go實現(xiàn)用戶每日限額的方法(例一天只能領三次福利)

    Go實現(xiàn)用戶每日限額的方法(例一天只能領三次福利)

    這篇文章主要介紹了Go實現(xiàn)用戶每日限額的方法(例一天只能領三次福利)
    2022-01-01
  • Go語言的管道Channel用法實例

    Go語言的管道Channel用法實例

    這篇文章主要介紹了Go語言的管道Channel用法,實例分析了Go語言中管道的原理與使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-02-02
  • Golang使用Gin創(chuàng)建Restful API的實現(xiàn)

    Golang使用Gin創(chuàng)建Restful API的實現(xiàn)

    本文主要介紹了Golang使用Gin創(chuàng)建Restful API的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01
  • Golang 統(tǒng)計字符串字數(shù)的方法示例

    Golang 統(tǒng)計字符串字數(shù)的方法示例

    本篇文章主要介紹了Golang 統(tǒng)計字符串字數(shù)的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • Go語言中的switch用法實例分析

    Go語言中的switch用法實例分析

    這篇文章主要介紹了Go語言中的switch用法,實例分析了switch的功能及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-02-02
  • GoLang內(nèi)存模型詳細講解

    GoLang內(nèi)存模型詳細講解

    go官方介紹go內(nèi)存模型的時候說:探究在什么條件下,goroutine 在讀取一個變量的值的時,能夠看到其它 goroutine 對這個變量進行的寫的結果,Go內(nèi)存模型規(guī)定了一些條件,在這些條件下,在一個goroutine中讀取變量返回的值能夠確保是另一個goroutine中對該變量寫入的值
    2022-12-12
  • GoFrame基于性能測試得知grpool使用場景

    GoFrame基于性能測試得知grpool使用場景

    這篇文章主要為大家介紹了GoFrame基于性能測試得知grpool使用場景示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Go設計模式之原型模式圖文詳解

    Go設計模式之原型模式圖文詳解

    原型模式是一種創(chuàng)建型設計模式, 使你能夠復制已有對象, 而又無需使代碼依賴它們所屬的類,本文將通過圖片和文字讓大家可以詳細的了解Go的原型模式,感興趣的通過跟著小編一起來看看吧
    2023-07-07

最新評論