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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?