1. func main() {
    2. router := gin.Default()
    3. // 将指定文件夹注册到route
    4. router.Static("/assets", "./assets") // ./assets是文件夹目录
    5. //将指定文件夹中的文件注册到route
    6. router.StaticFS("/more_static", http.Dir("my_file_system"))
    7. // 将指定文件注册到route
    8. router.StaticFile("/favicon.ico", "./resources/favicon.ico")
    9. // 将指定文件注册到route
    10. router.GET("/local/file", func(c *gin.Context) {
    11. c.File("local/file.go")
    12. })
    13. // Listen and serve on 0.0.0.0:8080
    14. router.Run(":8080")
    15. }

    文件转发

    1. func main() {
    2. router := gin.Default()
    3. router.GET("/someDataFromReader", func(c *gin.Context) {
    4. response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
    5. if err != nil || response.StatusCode != http.StatusOK {
    6. c.Status(http.StatusServiceUnavailable)
    7. return
    8. }
    9. reader := response.Body
    10. contentLength := response.ContentLength
    11. contentType := response.Header.Get("Content-Type")
    12. extraHeaders := map[string]string{
    13. "Content-Disposition": `attachment; filename="gopher.png"`,
    14. }
    15. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
    16. })
    17. router.Run(":8080")
    18. }