2 回答
TA貢獻1884條經驗 獲得超4個贊
引用原始杜松子酒文檔:https://github.com/gin-gonic/gin#serving-static-files
func main() {
router := gin.Default()
router.Static("/assets", "./assets")
router.StaticFS("/more_static", http.Dir("my_file_system"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}
因此基本上您應該在您定義的其他路由旁邊定義一個特定于 JSON 文件的路由。然后使用它。
TA貢獻1804條經驗 獲得超2個贊
如果你想根據查詢路徑提供靜態文件,你可以這樣做:
func serve() {
r := gin.Default()
r.GET("/*path", func(c *gin.Context) {
// read from file
data, err := os.ReadFile("/path/to/file")
if err != nil {
// error handler
}
switch path.Ext(c.Request.URL.Path) {
case ".html":
c.Header("Content-Type", "text/html")
case ".css":
c.Header("Content-Type", "text/css")
case ".js":
c.Header("Content-Type", "application/javascript")
// ...
}
_, _ = c.Writer.Write(data)
})
// Listen and serve on 0.0.0.0:8080
panic(r.Run(":8080"))
}
- 2 回答
- 0 關注
- 216 瀏覽
添加回答
舉報
