Golang使用embed打包gin应用

历史是一堆灰烬,但灰烬深处有余温。

文件目录

1
2
3
4
5
6
7
- static
- js
- 1.js
- templates
- foo.html
- index.html
- main.go

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
"embed"
"github.com/gin-gonic/gin"
"html/template"
"net/http"
)

//go:embed static templates

var f embed.FS

func main(){

router := gin.Default()
templ := template.Must(template.New("").ParseFS(f, "templates/*.html"))
router.SetHTMLTemplate(templ)

// example: /public/static/js/1.js
router.StaticFS("/public", http.FS(f))


router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Embed Demo",
})
})

router.GET("/foo", func(c *gin.Context) {
c.HTML(http.StatusOK, "foo.html", gin.H{
"title": "Foo Bar",
})
})

_ = router.Run(":9080")
}


1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="/public/static/js/1.js"></script>
</head>
<body>
<h1>htn</h1>
</body>
</html>