doy51723 2016-12-07 08:23
浏览 79
已采纳

Golang单页网站服务器[重复]

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

</div>
  • 写回答

1条回答 默认 最新

  • dsorecdf78171 2016-12-07 12:29
    关注

    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 != "/" {
           w.WriteHeader(http.StatusNotFound)
           // Write custom 404 Page to w.Write()
            return
        }
        // Handling for route /
    }
    

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

    Eg.

    In httprouter you set httprouter.Router.NotFound

    OR

    In gorilla/mux you set mix.Router.NotFoundHandler

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题