go-zero部署静态资源页面

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

  

posted @ 2022-05-17 16:01  wcu1117  阅读(1088)  评论(0编辑  收藏  举报