提供靜態檔案
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")}