Loading... 1、入口启动文件,定义静态资源路由 ```go //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) } } ``` ### 2 ```go server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/book-qr-code/img/:name", Handler: func(w http.ResponseWriter, r *http.Request) { //fmt.Printf("进入路由 r.URL.Path: %s\n", r.URL.Path) http.ServeFile(w, r, "img/"+strings.TrimPrefix(r.URL.Path, "/book-qr-code/img/"))// img 是本地图片目录 }, }) ``` > https://github.com/zeromicro/go-zero/issues/3716 # 参考其他人的方式 我感觉这种不错 ```go func dirHandler(prefix, fileDir string) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { handler := http.StripPrefix(prefix, http.FileServer(http.Dir(fileDir))) handler.ServeHTTP(w, req) } } func registerHandlers(engine *rest.Server, prefix, dirPath string) { // Set up the dir level dirLevel := []string{":1", ":2", ":3", ":4", ":5", ":6", ":7", ":8"} for i := 1; i < len(dirLevel); i++ { path := prefix + strings.Join(dirLevel[:i], "/") engine.AddRoute( rest.Route{ Method: http.MethodGet, Path: path, Handler: dirHandler(prefix, dirPath), }) } } ``` 最后修改:2024 年 11 月 11 日 © 允许规范转载 打赏 赞赏作者 微信 赞 2 如果觉得我的文章对你有用,请随意赞赏
1 条评论
https://github.com/zeromicro/go-zero/issues/3716