golang常用代码片
Easul Lv4

嵌入静态文件到二进制包中

折叠代码块GOLANG 复制代码
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// 项目结构如下
// ├── go.mod
// ├── go.sum
// ├── main.go
// └── static
// ├── assets
// │ └── index.js
// └── index.html
package main

import (
"embed"
"fmt"
"net/http"
"strings"
)

// 用于将所有 static 文件夹下的静态文件嵌入进来
//go:embed static/*
var staticFiles embed.FS

func main() {
serveIndexPage()
addAllAssets("static")
fmt.Println("Listen:8083...")
err := http.ListenAndServe(":8083", nil)
if err != nil {
fmt.Println(err.Error())
}
}

func serveIndexPage() {
// 这里用于指定不加 index.html 的路径时的情况,否则访问根路径将无法返回任何东西
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
indexHTML, err := staticFiles.ReadFile("static/index.html")
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Fprint(w, string(indexHTML))
})
}

// 通过从静态文件的根路径一个一个递归的读取文件,为每个文件指定路由路径
func addAllAssets(rootPath string) {
files, err := staticFiles.ReadDir(rootPath)
if err != nil {
panic(err)
}
for _, file := range files {
if file.IsDir() {
addAllAssets(rootPath + "/" + file.Name())
continue
}
filePath := rootPath + "/" + file.Name()
http.HandleFunc(strings.Replace(filePath, "static", "", 1), handleAssets(filePath))
}
}

func handleAssets(filePath string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
indexHTML, err := staticFiles.ReadFile(filePath)
if err != nil {
// http.Error(w, "404 Not Found", http.StatusNotFound)
fmt.Println(err.Error())
return
}
if strings.Contains(filePath, ".html") {
w.Header().Set("content-type", "text/html; chatset=utf-8")
}
if strings.Contains(filePath, ".js") {
w.Header().Set("content-type", "application/javascript")
}
if strings.Contains(filePath, ".css") {
w.Header().Set("content-type", "text/css")
}
if strings.Contains(filePath, ".png") {
w.Header().Set("content-type", "image/png")
}
if strings.Contains(filePath, ".txt") {
w.Header().Set("content-type", "text/plain")
}
fmt.Fprint(w, string(indexHTML))
}
}

托管HTTP服务的几种方法

直接使用http包

折叠代码块GOLANG 复制代码
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"
"fmt"
"net/http"
)

// 引入需要嵌入golang二进制包中的文件
//go:embed static/*
var staticFiles embed.FS

func main() {
// 指定路由,并通过传入的 func(http.ResponseWriter, *http.Request) 签名的函数处理请求与响应
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
indexHTML, err := staticFiles.ReadFile("static/index.html")
if err != nil {
fmt.Println(err.Error())
return
}
w.Header().Set("content-type", "text/html; chatset=utf-8")
fmt.Fprint(w, string(indexHTML))
})
// 指定监听端口,提供服务
err := http.ListenAndServe(":8083", nil)
if err != nil {
fmt.Println(err.Error())
}
}
 评论
来发评论吧~
Powered By Valine
v1.5.2