docs(readme): Using the embed package as a recommended example that build a single binary with templates (#3379)

This commit is contained in:
mstmdev 2022-11-09 14:50:46 +08:00 committed by GitHub
parent 212267d671
commit a0acf1df28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1884,48 +1884,56 @@ func main() {
### Build a single binary with templates ### Build a single binary with templates
You can build a server into a single binary containing templates by using [go-assets][]. You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.
[go-assets]: https://github.com/jessevdk/go-assets
```go ```go
package main
import (
"embed"
"html/template"
"net/http"
"github.com/gin-gonic/gin"
)
//go:embed assets/* templates/*
var f embed.FS
func main() { func main() {
r := gin.New() router := gin.Default()
templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))
router.SetHTMLTemplate(templ)
t, err := loadTemplate() // example: /public/assets/images/example.png
if err != nil { router.StaticFS("/public", http.FS(f))
panic(err)
}
r.SetHTMLTemplate(t)
r.GET("/", func(c *gin.Context) { router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "/html/index.tmpl",nil) c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
})
}) })
r.Run(":8080")
}
// loadTemplate loads templates embedded by go-assets-builder router.GET("/foo", func(c *gin.Context) {
func loadTemplate() (*template.Template, error) { c.HTML(http.StatusOK, "bar.tmpl", gin.H{
t := template.New("") "title": "Foo website",
for name, file := range Assets.Files { })
defer file.Close() })
if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
continue router.GET("favicon.ico", func(c *gin.Context) {
} file, _ := f.ReadFile("assets/favicon.ico")
h, err := ioutil.ReadAll(file) c.Data(
if err != nil { http.StatusOK,
return nil, err "image/x-icon",
} file,
t, err = t.New(name).Parse(string(h)) )
if err != nil { })
return nil, err
} router.Run(":8080")
}
return t, nil
} }
``` ```
See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary` directory. See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.
### Bind form-data request with custom struct ### Bind form-data request with custom struct