duanlu4371 2019-06-19 19:28
浏览 51
已采纳

如何使用go服务(正确)反应路由器?

Im trying to serve a react-router with go, i already did it, but i'm having troubles, i think the way i did is not the correct one, or it's not complete. Im using Mux. The trouble im having is that when i push the <Link>'s in my app it changes de view correctly, but when i try to change it directly from the browser or i try to reload the page i get a 404 error

I've tried diferent ways, im actually doing this way:

func main() {

    var dir = "./static"

    router := mux.NewRouter()

    fs := http.FileServer(http.Dir(dir))
    router.PathPrefix("/").Handler(fs)


    fmt.Println("Server running in port :8000")

    log.Fatal(http.ListenAndServe(":8000", router))

}

I want the server to serve the same directory in all request like "/", "/example", "/example2", etc.

  • 写回答

1条回答 默认 最新

  • doulangxun7769 2019-06-19 22:33
    关注

    My guess is that you have some static content and you'd like everything else to forward to the index.html. I had a similar problem, and my solution was to just prefix all the react-router urls with a constant so I could detect that on the backend and forward it. My code looks something like this:

    router := mux.NewRouter()
    router.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
    router.HandleFunc("/", handleIndex).Methods("GET")
    router.HandleFunc("/h/{param:.*}", handleIndex).Methods("GET")
    

    And in my react-router I just changed all the routes from {uri} to /h/{uri}

    If you really want to forward everything to the react code without any backend checking for 404s or anything, you could do:

    router := mux.NewRouter()
    router.NotFoundHandler = ... // Write a function to serve the index file here
    fs := http.FileServer(http.Dir(dir))
    router.PathPrefix("/").Handler(fs)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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,如何解決?
  • ¥15 c++头文件不能识别CDialog