The go language converts strings to file streams and downloads files through http requests

Use the gin component

go get -u  github.com/gin-gonic/gin

download method

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
}

create route


func main() {
    
    
	//创建路由
	r :=gin.Default()
	v2 := r.Group("/")
	{
    
    
		//限制文件大小,默认32M,限制为1M
		r.MaxMultipartMemory = 1 << 20
		v2.GET("/downpem",service.FileDownload)
	}
	r.Run(":8888")

}

operation result

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/ydl1128/article/details/127696747