本文主要是介绍gin框架36--静态资源嵌入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
gin框架36--静态资源嵌入
- 介绍
- 案例
- 说明
介绍
本文主要介绍gin框架中如何使用静态资源嵌入。
案例
源码:
vim main.go
package mainimport ("html/template""io/ioutil""net/http""strings""github.com/gin-gonic/gin"
)func main() {r := gin.New()t, err := loadTemplate()if err != nil {panic(err)}r.SetHTMLTemplate(t)r.GET("/", func(c *gin.Context) {c.HTML(http.StatusOK, "/html/index.tmpl", gin.H{"Foo": "World",})})r.GET("/bar", func(c *gin.Context) {c.HTML(http.StatusOK, "/html/bar.tmpl", gin.H{"Bar": "World",})})r.Run(":8080")
}func loadTemplate() (*template.Template, error) {t := template.New("")for name, file := range Assets.Files {if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {continue}h, err := ioutil.ReadAll(file)if err != nil {return nil, err}t, err = t.New(name).Parse(string(h))if err != nil {return nil, err}}return t, nil
}vim assets.go
package mainimport ("time""github.com/jessevdk/go-assets"
)var _Assetsbfa8d115ce0617d89507412d5393a462f8e9b003 = "<!doctype html>\n<body>\n <p>Can you see this? → {{.Bar}}</p>\n</body>\n"
var _Assets3737a75b5254ed1f6d588b40a3449721f9ea86c2 = "<!doctype html>\n<body>\n <p>Hello, {{.Foo}}</p>\n</body>\n"// Assets returns go-assets FileSystem
var Assets = assets.NewFileSystem(map[string][]string{"/": {"html"}, "/html": {"bar.tmpl", "index.tmpl"}}, map[string]*assets.File{"/": {Path: "/",FileMode: 0x800001ed,Mtime: time.Unix(1524365738, 1524365738517125470),Data: nil,}, "/html": {Path: "/html",FileMode: 0x800001ed,Mtime: time.Unix(1524365491, 1524365491289799093),Data: nil,}, "/html/bar.tmpl": {Path: "/html/bar.tmpl",FileMode: 0x1a4,Mtime: time.Unix(1524365491, 1524365491289611557),Data: []byte(_Assetsbfa8d115ce0617d89507412d5393a462f8e9b003),}, "/html/index.tmpl": {Path: "/html/index.tmpl",FileMode: 0x1a4,Mtime: time.Unix(1524365491, 1524365491289995821),Data: []byte(_Assets3737a75b5254ed1f6d588b40a3449721f9ea86c2),}}, "")
html
vim html/index.tmpl
<!doctype html>
<body><p>Hello, {{.Foo}}</p>
</body>vim html/bar.tmpl
<!doctype html>
<body><p>Can you see this? → {{.Bar}}</p>
</body>
测试:
http://127.0.0.1:8080
http://127.0.0.1:8080/bar
说明
gin官方文档 静态资源嵌入
gin-gonic/examples/assets-in-binary/example01
github.com/jessevdk/go-assets
这篇关于gin框架36--静态资源嵌入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!