func main() {
router := gin.Default()
// 将指定文件夹注册到route
router.Static("/assets", "./assets") // ./assets是文件夹目录
//将指定文件夹中的文件注册到route
router.StaticFS("/more_static", http.Dir("my_file_system"))
// 将指定文件注册到route
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// 将指定文件注册到route
router.GET("/local/file", func(c *gin.Context) {
c.File("local/file.go")
})
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}
文件转发
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")
}