使用gin组件
go get -u github.com/gin-gonic/gin
下载方法
func FileDownload(c *gin.Context) {
filename := time.Now().String() + ".txt"
//此处可以改为请求下载一个文件,将返回res.Body作为文件流即可
i := []byte("哈哈哈哈哈")
reader := bytes.NewReader(i)
response := c.Writer
//此处是关键
response.Header().Set("Content-Type", "application/octet-stream")
response.Header().Set("Content-Disposition", "attachment;filename="+filename)
b, err := ioutil.ReadAll(reader)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
}
_, err = response.Write(b)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
}
return
}
创建路由
func main() {
//创建路由
r :=gin.Default()
v2 := r.Group("/")
{
//限制文件大小,默认32M,限制为1M
r.MaxMultipartMemory = 1 << 20
v2.GET("/downpem",service.FileDownload)
}
r.Run(":8888")
}
运行结果