Gin 使用示例(六):使用 HTML 模板构建二进制文件
这里我们使用 jessevdk/go-assets 将小的资源文件从磁盘加载到内存,这对包含前端资源的应用做单个二进制文件部署非常有用。
准备工作:
go get github.com/jessevdk/go-assets-builder
在 templates
目录下创建 html
子目录存放模板文件,在 html
下创建 index.tmpl
:
<!doctype html>
<body>
<p>Hello, {{.Foo}}</p>
</body>
生成 assets.go
:
go-assets-builder templates/html -o assets.go
对应的源码如下(src/gin-demo/examples/assets.go
):
package main
import (
"time"
"github.com/jessevdk/go-assets"
)
var _Assets90ba780e7ce0fde2c751eedf5fb441ba62ac6407 = "<!doctype html>\n<body>\n <p>Hello, {{.Foo}}</p>\n</body>"
// Assets returns go-assets FileSystem
var Assets = assets.NewFileSystem(map[string][]string{"/": []string{"templates"}, "/templates": []string{"html"}, "/templates/html": []string{"index.tmpl"}}, map[string]*assets.File{
"/": &assets.File{
Path: "/",
FileMode: 0x800001ed,
Mtime: time.Unix(1578364740, 1578364740503757153),
Data: nil,
}, "/templates": &assets.File{
Path: "/templates",
FileMode: 0x800001ed,
Mtime: time.Unix(1578364512, 1578364512733855968),
Data: nil,
}, "/templates/html": &assets.File{
Path: "/templates/html",
FileMode: 0x800001ed,
Mtime: time.Unix(1578364878, 1578364878533953215),
Data: nil,
}, "/templates/html/index.tmpl": &assets.File{
Path: "/templates/html/index.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1578364844, 1578364844236729998),
Data: []byte(_Assets90ba780e7ce0fde2c751eedf5fb441ba62ac6407),
}}, "")
编写 Web 服务器处理代码如下(src/gin-demo/examples/template.go
):
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"io/ioutil"
"net/http"
"strings"
)
// loadTemplate loads templates embedded by go-assets-builder
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
}
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, "/templates/html/index.tmpl", gin.H{
"Foo": "学院君",
})
})
r.Run(":8080")
}
编译代码生成二进制文件:
go build -o assets-in-binary assets.go template.go
启动服务器:
通过 curl 请求测试:
也可以在浏览器中访问:
2 Comments
command-line-arguments
./template.go:13:26: undefined: Assets
Compilation finished with exit code 2
template.go 和 assets.go 是在同一个目录下并且属于同一个包吗