go-zero部署静态资源页面

1、入口启动文件,定义静态资源路由

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
//main直接调用
//静太文件处理
staticFileHandler(server)
 
//定义函数
func staticFileHandler(engine *rest.Server) {
    //这里注册
    patern := "web"
    dirpath := "web/assets/"
 
    rd, err := ioutil.ReadDir(dirpath)
 
    //添加进路由最后生成 /asset
    engine.AddRoutes(
        []rest.Route{
            {
                Method:  http.MethodGet,
                Path:    "/index.html",
                Handler: dirhandler("index.html", patern),
            },
            {
                Method:  http.MethodGet,
                Path:    "/",
                Handler: dirhandler("/", patern),
            },
            {
                Method:  http.MethodGet,
                Path:    "/favicon.ico",
                Handler: dirhandler("/favicon.ico", patern),
            },
        })
    for _, f := range rd {
        filename := f.Name()
        path := "/assets/" + filename
        //最后生成 /asset
        engine.AddRoute(
            rest.Route{
                Method:  http.MethodGet,
                Path:    path,
                Handler: dirhandler("/assets/", dirpath),
            })
    }
 
}
 
func dirhandler(patern, filedir string) http.HandlerFunc {
    return func(w http.ResponseWriter, req *http.Request) {
        handler := http.StripPrefix(patern, http.FileServer(http.Dir(filedir)))
        handler.ServeHTTP(w, req)
    }
}

  

posted @   wcu1117  阅读(1134)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示