go-zero映射静态资源页面

1,164 阅读1分钟

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

//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)
    }
}