安装
go get -u github.com/gobuffalo/packr/packr
go get -u github.com/gobuffalo/packr
当前目录:
[root@localhost d0116]# tree
.
├── go.mod
├── go.sum
├── static
│ ├── index2.html
│ ├── index.html
│ └── js
│ └── example.js
└── x.go
执行packr
[root@localhost d0116]# packr
[root@localhost d0116]# tree
.
├── a_main-packr.go
├── go.mod
├── go.sum
├── static
│ ├── index2.html
│ ├── index.html
│ └── js
│ └── example.js
└── x.go
2 directories, 7 files
build构建
[root@localhost d0116]# go build x.go a_main-packr.go
[root@localhost d0116]# tree
.
├── a_main-packr.go
├── go.mod
├── go.sum
├── static
│ ├── index2.html
│ ├── index.html
│ └── js
│ └── example.js
├── x
└── x.go
2 directories, 8 files
之后可执行文件x在任何位置都可以执行,不依赖于静态资源。
测试如下:
[root@localhost ~]# curl http://192.168.150.53:8080/js/example.js
var word = "Hello, itbsl";
alert(word);[root@localhost ~]#
[root@localhost ~]# curl http://192.168.150.53:8080/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<script type="text/javascript" src="js/example.js"></script>
</head>
<body>
helloworld
</body>
</html>[root@localhost ~]#
源码:
[root@localhost d0116]# cat x.go
package main
import (
"net/http"
"github.com/gobuffalo/packr"
)
func main() {
// dist 目录下拥有前端用vue打包好的一系列静态资源
box := packr.NewBox("./static")
http.Handle("/", http.FileServer(box))
http.ListenAndServe(":8080", nil)
}
/*
1.packr
2.go build x.go a_main-packr.go
*/
[root@localhost d0116]# cat a_main-packr.go
// Code generated by github.com/gobuffalo/packr. DO NOT EDIT.
package main
import "github.com/gobuffalo/packr"
// You can use the "packr clean" command to clean up this,
// and any other packr generated files.
func init() {
packr.PackJSONBytes("./static", "index.html", "\"PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ImVuIj4KPGhlYWQ+CiAgICA8bWV0YSBjaGFyc2V0PSJVVEYtOCI+CiAgICA8dGl0bGU+dGl0bGU8L3RpdGxlPgoKICAgIDxzY3JpcHQgdHlwZT0idGV4dC9qYXZhc2NyaXB0IiBzcmM9ImpzL2V4YW1wbGUuanMiPjwvc2NyaXB0PgoKPC9oZWFkPgo8Ym9keT4KaGVsbG93b3JsZAo8L2JvZHk+CjwvaHRtbD4=\"")
packr.PackJSONBytes("./static", "index2.html", "\"PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ImVuIj4KPGhlYWQ+CiAgICA8bWV0YSBjaGFyc2V0PSJVVEYtOCI+CiAgICA8dGl0bGU+dGl0bGU8L3RpdGxlPgo8L2hlYWQ+Cjxib2R5PgpoZWxsb3dvcmxkMgo8L2JvZHk+CjwvaHRtbD4=\"")
packr.PackJSONBytes("./static", "js/example.js", "\"dmFyIHdvcmQgPSAiSGVsbG8sIGl0YnNsIjsKYWxlcnQod29yZCk7\"")
}
[root@localhost d0116]# cd static/
[root@localhost static]# ll
total 12
-rw-r--r--. 1 root root 134 Jan 16 20:41 index2.html
-rw-r--r--. 1 root root 200 Jan 16 20:36 index.html
drwxr-xr-x. 2 root root 4096 Jan 16 20:37 js
[root@localhost static]# cat js/example.js
var word = "Hello, itbsl";
alert(word);[root@localhost static]#
[root@localhost static]#
[root@localhost static]# cat index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<script type="text/javascript" src="js/example.js"></script>
</head>
<body>
helloworld
</body>
参考
https://www.xhyonline.com/?p=1161