背景:
本文实践从reader保存数据
代码
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/someDataFromReader", 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(":8080")
}
服务端运行代码,
客户端模拟访问,可以看到访问到了数据

本文介绍如何使用Gin框架从Reader保存数据。通过示例代码展示了一个HTTP服务,该服务从远程URL获取数据并将其保存为本地文件。具体实现包括使用http.Get请求数据,检查响应状态,读取响应体,设置Content-Length、Content-Type和Content-Disposition头,最后使用c.DataFromReader方法将数据保存到本地。
1550

被折叠的 条评论
为什么被折叠?



