drnzpd579935 2018-04-24 18:08
浏览 56
已采纳

如何设置服务ReactJS应用程序的路由?

I'm trying to set up a route to serve my reactjs application.

I have my index.html and bundle.js in the public folder

/public/index.html
/public/bundle.js

I'm using go as my backend API, and also to serve my reactjs app.

I created a subroute for my app like:

r := mux.NewRouter()

app := r.Host("app.example.com").Subrouter()

So any request with app as the subdomain will be for my Reactjs app.

So now I have to serve every request regardless of the URL to my reactjs app.

Is path prefix what I need here?

I tried this:

app.PathPrefix("/").Handler(serveReact)

func serveReact(w http.ResponseWriter, r *http.Request) {
}

But I get this error:

cannot use serveReact (type func() http.Handler) as type http.Handler in argument to app.PathPrefix("/").Handler: func() http.Handler does not implement http.Handler (missing ServeHTTP method)

  • 写回答

1条回答 默认 最新

  • doubu5035 2018-04-24 18:35
    关注

    Your http handler needs a ServeHTTP method. If you pass your function to http.HandlerFunc, that will be introduced for you:

    app.PathPrefix("/").Handler(http.HandlerFunc(serveReact))
    
    func serveReact(w http.ResponseWriter, r *http.Request) {
    }
    

    The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

    source

    type HandlerFunc func(ResponseWriter, *Request)
    
    // ServeHTTP calls f(w, r).
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
        f(w, r)
    }
    

    Similarly, you could use the mux router HandlerFunc instead:

    app.PathPrefix("/").HandlerFunc(serveReact)
    
    func serveReact(w http.ResponseWriter, r *http.Request) {
    }
    

    This essentially performs both steps for you in a combined single step.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名