提供静态文件
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")}