doucheng1944 2016-08-28 23:39
浏览 29
已采纳

没有路线与大猩猩匹配时提供文件?

I'm using Gorilla Mux as my web server.

I define a bunch of routes, but if no route is matched, I want it to serve my index.html file.

func (mgr *ApiMgr) InstantiateRestRtr() *mux.Router {
    mgr.pRestRtr = mux.NewRouter().StrictSlash(true)
    mgr.pRestRtr.PathPrefix("/api/").Handler(http.StripPrefix("/api/",
        http.FileServer(http.Dir(mgr.fullPath+"/docsui"))))

    for _, route := range mgr.restRoutes {
        var handler http.Handler
        handler = Logger(route.HandlerFunc, route.Name)
        mgr.pRestRtr.Methods(route.Method)
          .Path(route.Pattern)
          .Name(route.Name)
          .Handler(handler)
    }

    // Here I want to catch any unmatched routes, and serve my '/site/index.html` file. 
    // How can I do this?

    return mgr.pRestRtr
}
  • 写回答

2条回答 默认 最新

  • douxian1923 2016-08-29 13:38
    关注

    You don't need to override the 404 behaviour. Use PathPrefix as a catch-all route, adding it after all other routes.

    func main() {
        var entry string
        var static string
        var port string
    
        flag.StringVar(&entry, "entry", "./index.html", "the entrypoint to serve.")
        flag.StringVar(&static, "static", ".", "the directory to serve static files from.")
        flag.StringVar(&port, "port", "8000", "the `port` to listen on.")
        flag.Parse()
    
        r := mux.NewRouter()
    
        // Note: In a larger application, we'd likely extract our route-building logic into our handlers
        // package, given the coupling between them.
    
        // It's important that this is before your catch-all route ("/")
        api := r.PathPrefix("/api/v1/").Subrouter()
        api.HandleFunc("/users", GetUsersHandler).Methods("GET")
    
        // Serve static assets directly.
        r.PathPrefix("/dist").Handler(http.FileServer(http.Dir(static)))
    
        // Catch-all: Serve our JavaScript application's entry-point (index.html).
        r.PathPrefix("/").HandlerFunc(IndexHandler(entry))
    
        srv := &http.Server{
            Handler: handlers.LoggingHandler(os.Stdout, r),
            Addr:    "127.0.0.1:" + port,
            // Good practice: enforce timeouts for servers you create!
            WriteTimeout: 15 * time.Second,
            ReadTimeout:  15 * time.Second,
        }
    
        log.Fatal(srv.ListenAndServe())
    }
    
    func IndexHandler(entrypoint string) func(w http.ResponseWriter, r *http.Request) {
        fn := func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, entrypoint)
        }
    
        return http.HandlerFunc(fn)
    }
    

    Shameless plug: I blogged on this here: http://elithrar.github.io/article/vue-react-ember-server-golang/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件