mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-24 02:32:17 +08:00
Add example to build single binary with templates
This commit is contained in:
parent
dfe37ea6f1
commit
1895100955
33
examples/assets-in-binary/README.md
Normal file
33
examples/assets-in-binary/README.md
Normal file
@ -0,0 +1,33 @@
|
||||
# Building a single binary containing templates
|
||||
|
||||
This is a complete example to create a single binary with the
|
||||
[gin-gonic/gin][gin] Web Server with HTML templates.
|
||||
|
||||
[gin]: https://github.com/gin-gonic/gin
|
||||
|
||||
## How to use
|
||||
|
||||
### Prepare Packages
|
||||
|
||||
```
|
||||
go get github.com/gin-gonic/gin
|
||||
go get github.com/jessevdk/go-assets-builder
|
||||
```
|
||||
|
||||
### Generate assets.go
|
||||
|
||||
```
|
||||
go-assets-builder html -o assets.go
|
||||
```
|
||||
|
||||
### Build the server
|
||||
|
||||
```
|
||||
go build -o assets-in-binary
|
||||
```
|
||||
|
||||
### Run
|
||||
|
||||
```
|
||||
./assets-in-binary
|
||||
```
|
4
examples/assets-in-binary/html/bar.tmpl
Normal file
4
examples/assets-in-binary/html/bar.tmpl
Normal file
@ -0,0 +1,4 @@
|
||||
<!doctype html>
|
||||
<body>
|
||||
<p>Can you see this? → {{.Bar}}</p>
|
||||
</body>
|
4
examples/assets-in-binary/html/index.tmpl
Normal file
4
examples/assets-in-binary/html/index.tmpl
Normal file
@ -0,0 +1,4 @@
|
||||
<!doctype html>
|
||||
<body>
|
||||
<p>Hello, {{.Foo}}</p>
|
||||
</body>
|
48
examples/assets-in-binary/main.go
Normal file
48
examples/assets-in-binary/main.go
Normal file
@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"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
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user