github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ginx/anyfn/dl.go (about) 1 package anyfn 2 3 import ( 4 "mime" 5 "path/filepath" 6 7 "github.com/gin-gonic/gin" 8 ) 9 10 // DlFile represents the file to be downloaded. 11 type DlFile struct { 12 DiskFile string 13 Filename string 14 Content []byte 15 } 16 17 // Deal is the processor for a specified type. 18 func (d DlFile) Deal(c *gin.Context) { 19 c.Header("Content-Disposition", d.createContentDisposition()) 20 c.Header("Content-Description", "File Transfer") 21 c.Header("Content-Type", "application/octet-stream") 22 c.Header("Content-Transfer-Encoding", "binary") 23 c.Header("Expires", "0") 24 c.Header("Cache-Control", "must-revalidate") 25 c.Header("Pragma", "public") 26 27 if d.DiskFile != "" { 28 c.File(d.DiskFile) 29 return 30 } 31 32 _, _ = c.Writer.Write(d.Content) 33 } 34 35 func (d DlFile) createContentDisposition() string { 36 m := map[string]string{"filename": d.getDownloadFilename()} 37 return mime.FormatMediaType("attachment", m) 38 } 39 40 func (d DlFile) getDownloadFilename() string { 41 filename := d.Filename 42 43 if filename == "" { 44 filename = filepath.Base(d.DiskFile) 45 } 46 47 if filename == "" { 48 return "dl" 49 } 50 51 return filename 52 }