@@ -1884,48 +1884,56 @@ func main() {
18841884
18851885### Build a single binary with templates
18861886
1887- You can build a server into a single binary containing templates by using [ go-assets] [ ] .
1888-
1889- [ go-assets ] : https://github.com/jessevdk/go-assets
1887+ You can build a server into a single binary containing templates by using the [ embed] ( https://pkg.go.dev/embed ) package.
18901888
18911889``` go
1890+ package main
1891+
1892+ import (
1893+ " embed"
1894+ " html/template"
1895+ " net/http"
1896+
1897+ " github.com/gin-gonic/gin"
1898+ )
1899+
1900+ // go:embed assets/* templates/*
1901+ var f embed.FS
1902+
18921903func main () {
1893- r := gin.New ()
1904+ router := gin.Default ()
1905+ templ := template.Must (template.New (" " ).ParseFS (f, " templates/*.tmpl" , " templates/foo/*.tmpl" ))
1906+ router.SetHTMLTemplate (templ)
18941907
1895- t , err := loadTemplate ()
1896- if err != nil {
1897- panic (err)
1898- }
1899- r.SetHTMLTemplate (t)
1908+ // example: /public/assets/images/example.png
1909+ router.StaticFS (" /public" , http.FS (f))
19001910
1901- r.GET (" /" , func (c *gin.Context ) {
1902- c.HTML (http.StatusOK , " /html/index.tmpl" ,nil )
1911+ router.GET (" /" , func (c *gin.Context ) {
1912+ c.HTML (http.StatusOK , " index.tmpl" , gin.H {
1913+ " title" : " Main website" ,
1914+ })
19031915 })
1904- r.Run (" :8080" )
1905- }
19061916
1907- // loadTemplate loads templates embedded by go-assets-builder
1908- func loadTemplate () (*template .Template , error ) {
1909- t := template.New (" " )
1910- for name , file := range Assets.Files {
1911- defer file.Close ()
1912- if file.IsDir () || !strings.HasSuffix (name, " .tmpl" ) {
1913- continue
1914- }
1915- h , err := ioutil.ReadAll (file)
1916- if err != nil {
1917- return nil , err
1918- }
1919- t, err = t.New (name).Parse (string (h))
1920- if err != nil {
1921- return nil , err
1922- }
1923- }
1924- return t, nil
1917+ router.GET (" /foo" , func (c *gin.Context ) {
1918+ c.HTML (http.StatusOK , " bar.tmpl" , gin.H {
1919+ " title" : " Foo website" ,
1920+ })
1921+ })
1922+
1923+ router.GET (" favicon.ico" , func (c *gin.Context ) {
1924+ file , _ := f.ReadFile (" assets/favicon.ico" )
1925+ c.Data (
1926+ http.StatusOK ,
1927+ " image/x-icon" ,
1928+ file,
1929+ )
1930+ })
1931+
1932+ router.Run (" :8080" )
19251933}
19261934```
19271935
1928- See a complete example in the ` https://github.com/gin-gonic/examples/tree/master/assets-in-binary ` directory.
1936+ See a complete example in the ` https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02 ` directory.
19291937
19301938### Bind form-data request with custom struct
19311939
0 commit comments