An apple a day keeps the doctor away !

0%

golang embed 整合静态文件

go 的1.16版本整合了静态文件嵌入整合功能,本文做个记录。为什么要做静态文件整合?无外乎在于部署更简单。

How?

想要嵌入静态资源,首先我们得利用embed这个新的标准库。在声明静态资源的文件里我们需要引入这个库。

对于我们想要嵌入进程序的资源,需要使用//go:embed指令进行声明,注意//之后不能有空格。具体格式如下:

1
//go:embed pattern
Example

打包HTML

目录结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.
|-- favicon.ico
|-- go.mod
|-- main.go
|-- static
| |-- css
| | |-- FiraCode.css
| | `-- labulac.css
| `-- img
| `-- bg.jpg
`-- web
|-- index.html
`-- writing.go

4 directories, 8 files
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
package main

import (
"embed"
"log"
"net/http"
"os"
"webtest/web"
)

//go:embed favicon.ico
var favcionEmbedfile embed.FS

//go:embed static
var staticEmbedfiles embed.FS

func main() {

http.HandleFunc("/", web.Writing)
http.Handle("/static/", http.FileServer(http.FS(staticEmbedfiles)))
http.Handle("/favicon.ico", http.FileServer(http.FS(favcionEmbedfile)))

err := http.ListenAndServe(":8090", nil)
if err != nil {
log.Println("启动端口发生异常, 请检查端口是否被占用", err)
os.Exit(1)
}
}
writing.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
package web

import (
"embed"
"fmt"
"net/http"
"text/template"
)

//go:embed index.html
var indexEmbedFile embed.FS

type writingdata struct {
A string
}

func Writing(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFS(indexEmbedFile, "index.html")
if err != nil {
fmt.Println("Error happened..")
fmt.Println(err)
return
}
t.Execute(w, &writingdata{A: "111"})

}