跳到內容

提供靜態檔案

Gin 提供三種方法來提供靜態內容:

  • router.Static(relativePath, root) — 提供整個目錄。對 relativePath 的請求會映射到 root 下的檔案。例如,router.Static("/assets", "./assets") 會在 /assets/style.css 提供 ./assets/style.css
  • router.StaticFS(relativePath, fs) — 與 Static 類似,但接受 http.FileSystem 介面,讓你能更好地控制檔案的解析方式。當你需要從嵌入式檔案系統提供檔案或想要自訂目錄列表行為時使用此方法。
  • router.StaticFile(relativePath, filePath) — 提供單一檔案。適用於 /favicon.ico/robots.txt 等端點。
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
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")
}