Gin 使用示例(三十二):下载文件
由 学院君 创建于2年前, 最后更新于 2年前    版本号 #1    7183 views    1 likes    0 collects

示例代码:

func main() {
    router := gin.Default()
    router.GET("/dataFromReader", func(c *gin.Context) {
        response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
        if err != nil || response.StatusCode != http.StatusOK {
            c.Status(http.StatusServiceUnavailable)
            return
        }
    
        reader := response.Body
        contentLength := response.ContentLength
        contentType := response.Header.Get("Content-Type")
    
        extraHeaders := map[string]string{
            "Content-Disposition": `attachment; filename="gopher.png"`,
        }
    
        c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
    })
    router.Run(":8088")
}
/dataFromReader