2016-12-07 08:23



This question already has an answer here:

I'm trying to build some spa/spw with golang and react-router as the back-end, but I've encountered a little problem.

React-router seems to base itself around the idea that any "bad" request to the server (e.g. /path/dynamicRessourceHash ) delivers an .html page the user (said html page then imports the .js from the server) and react-router then kicks in, analyzes the path and gives the application the information needed to make fetch requests in the background and deliver the resources to the user.

So what would be the standard way to configure a server like this using "net/http" from std , that is, to server resources normally on pre-configured endpoints but treat all other endpoints as wildcards for one (or few) routes ?

Just to give an example (since today I seem to be bad with words). Say the user makes a request at:

/route1/whatever/someotherstuff?... etc whatever the things after the second "/" are I want the user to be served by the handler function for /route1/ (Note, i don't want the user to be redirected, since that fucks up the URL and consequently the client-side routing).

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dsorecdf78171 dsorecdf78171 5年前

    In net/http you can use the handler than serves the / route to return a 404 page since all unknown / unregistered routes match /.

    http.HandleFunc("/", handler)
    func handler(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
           // Write custom 404 Page to w.Write()
        // Handling for route /

    You could also use a different http multiplexer that supports Not Found Handlers.


    In httprouter you set httprouter.Router.NotFound


    In gorilla/mux you set mix.Router.NotFoundHandler

    点赞 评论 复制链接分享