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 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写