引入statik的包
- go get -d github.com/rakyll/statik
- go install github.com/rakyll/statik
main.go 头加上
//go:generate statik -src=./static
//go:generate go fmt statik/statik.go
package main
编译
- 在终端执行go generate
- 会在 statik 目录下生成statik.go
使用方法
chi 中示例
"github.com/rakyll/statik/fs"
_ "你的项目名称/statik" // 引入打包后的静态文件 statik.go
r := chi.NewRouter()
r.Get("/static/*", func(w http.ResponseWriter, r *http.Request) {
fs := http.StripPrefix("/static/", http.FileServer(statikFS))
fs.ServeHTTP(w, r)
})
gin中示例
"github.com/rakyll/statik/fs"
_ "你的项目名称/statik" // 引入打包后的静态文件 statik.go
statikFS,_ := fs.New()
r := gin.Default()
r.StaticFS("/static", statikFS)
r.GET("", func(c *gin.Context) {
t := template.Must(template.New("index").Parse(INDEXHTML))
t.ExecuteTemplate(c.Writer, "index", "")
})
r.GET("/favicon.ico",func (c *gin.Context){
read, err := http.FileSystem.Open("/favicon.ico")
if err != nil {}
defer read.Close()
io.Copy(c.Writer, read)
})
r.GET("/","index.html"同上)