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 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)