亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

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

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

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")
  //標(biāo)明傳輸文件類型
  //如果是其他類型,請(qǐng)參照: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是一個(gè)bytes.Buffer,則需調(diào)用b.Bytes()
  http.ServeContent(rw, c.Ctx.Request, "(文件名字)", time.Now(), bytes.NewReader(b.Bytes()))
}

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

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

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

  //最內(nèi)層用bytes.Buffer來(lái)進(jìn)行文件的存儲(chǔ)
  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, "")
  //下載后當(dāng)前文件的路徑設(shè)置
  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的關(guān)閉順序一定不能反
  tw.Close()
  gw.Close()

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

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

實(shí)現(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模版中插入一個(gè)特殊的替換字段,本例中為{Data_Json_Source}
  html = bytes.Replace(html, []byte("{Data_Json_Source}"), b.Bytes(), 1)

  // 將靜態(tài)文件添加進(jìn)html
  // 如果是.css,則前后增加<style></style>標(biāo)簽
  // 如果是.js,則前后增加<script><script>標(biāo)簽
  allStaticFiles := make([][]byte, 0)
  // jquery 需要最先進(jìn)行添加
  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格式進(jìn)行返回
  mf := &MyFile{
    Reader: bytes.NewReader(html),
    mif: myFileInfo{
      name: "report.html",
      data: html,
    },
  }
  var f http.File = mf
  return f
}

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

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

  tw := tar.NewWriter(gw)

  // 生成動(dòng)態(tài)report,并添加進(jìn)壓縮包
  // 調(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)全部實(shí)現(xiàn)了,前端部分如何接收呢,本例中我做了一個(gè)按鈕嵌套<a>標(biāo)簽來(lái)進(jìn)行請(qǐng)求:

<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">下載報(bào)表</button>
</a>

這樣,當(dāng)前端頁(yè)面中點(diǎn)擊下載報(bào)表按鈕之后,會(huì)自動(dòng)啟動(dòng)下載,下載我們后端傳回的report.tar.gz文件。

到此這篇關(guān)于Golang實(shí)現(xiàn)http server提供壓縮文件下載功能的文章就介紹到這了,更多相關(guān)Golang http server 壓縮下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

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

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

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

    Go語(yǔ)言讀取文件的方法小結(jié)

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

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

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

    Go語(yǔ)言的管道Channel用法實(shí)例

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

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

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

    Golang 統(tǒng)計(jì)字符串字?jǐn)?shù)的方法示例

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

    Go語(yǔ)言中的switch用法實(shí)例分析

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

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

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

    GoFrame基于性能測(cè)試得知grpool使用場(chǎng)景

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

    Go設(shè)計(jì)模式之原型模式圖文詳解

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

最新評(píng)論