drxm72811 2018-08-24 00:04
浏览 70

如何从golang中的确切网址重定向?

Whenever a request is made from localhost:9000/ I want to redirect the user to localhost:9000/#/trade/gem/GEM . The problem I am getting is that I get infinite redirects because "/" preceeds every url. How do I make it so that the user is only redirected if they visit the exact url of localhost:9000/ ? My code is below:

var newUrl string = "/#/trade/gem/GEM"

func handleRedirect(rw http.ResponseWriter, req *http.Request) {
    http.Redirect(rw, req, newUrl, http.StatusSeeOther)
}

func main() {
    http.Handle("/#/trade/", fs)
    http.HandleFunc("/", handleRedirect) //This is the exact url I want to redirect from
    http.ListenAndServe(":9000", nil)
}
  • 写回答

1条回答 默认 最新

  • doulan7166 2018-08-24 05:13
    关注

    When the / is registered then all the url will redirect to this until the other pattern is not registered.To solve this and handling only specific patterns you can write a custom handler and you can implement a logic where it redirects to the specific url whenever the localhost:9000/ is opened.

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    type Handler struct{}
    
    var NewUrl string = "/trade/gem/GEM"
    
    func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        uri := r.URL.Path
        if uri == "/" {
            http.Redirect(w, r, NewUrl, http.StatusSeeOther)
        }
        fmt.Fprintf(w, uri)
        return
    }
    
    func main() {
        handler := new(Handler)
        http.ListenAndServe(":9000", handler)
    }
    

    For more details check http.handler

    Note: You can not use # in the uri.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?