dsa80833 2016-01-29 00:16
浏览 78
已采纳

如何在HTTP包处理URL之前重写URL

With node/express its possible to do something like this

app.use(rewrite('/*', '/index.html'));

What would the equivalent in go be? I've tried using the httputil.ReverseProxy, but that seems entirely impractical.

  • 写回答

1条回答 默认 最新

  • doudou8081 2016-01-29 01:18
    关注

    For a simple "catch all" you can just do

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "index.html")
    })
    

    The "/" pattern matches everything.

    For a more complex pattern, you need to wrap your mux with a handler that rewrites the url.

    // register your handlers on a new mux
    mux := http.NewServeMux()
    mux.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
        // your handler code
    })
    
    ...
    
    rewrite := func(path string) string {
       // your rewrite code, returns the new path
    }
    
    ...
    
    // rewrite URL.Path in here before calling mux.ServeHTTP
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        r.URL.Path = rewrite(r.URL.Path) 
        mux.ServeHTTP(w,r)
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动