dscs63759 2016-08-08 21:54
浏览 162
已采纳

在Go中没有办法从https:// www ..重定向到https:// ..吗?

I saw this post by someone here but there are no answers: Redirecting https://www.domain.com to https://domain.com in Go

I tried to see if I could find a way to check if the request was made with a www url by checking the variables in *http.Request variable but all I got was relative paths and empty strings "".

I tried to fmt.Println() these variables:

func handleFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL.string())
    fmt.Println(r.Host)
    fmt.Println(r.RequestURI)
}

But none of these variables contained the absolute path with the www part. How can I check if a request was made from a www url? I want to figure this out so that I can redirect from www to non-www.

Is this really not even possible in Go? Some people suggested putting nginx in front of Go, but there has to be a way without nginx right? Do I really need to install and use nginx in front of Go just to do a simple redirect from www to non-www? This does not seem like a good solution to a seemingly small problem.

Is there no way to achieve this?

  • 写回答

1条回答 默认 最新

  • douqiang5933 2016-08-08 22:07
    关注

    Wrap your handlers with a redirector:

    func wwwRedirect(h http.Handler) http.Handler {
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if host := strings.TrimPrefix(r.Host, "www."); host != r.Host {
            // Request host has www. prefix. Redirect to host with www. trimmed.
            u := *r.URL
            u.Host = host
            u.Scheme = "https"
            http.Redirect(w, r, u.String(), http.StatusFound)
            return
        }
        h.ServeHTTP(w, r)
      })
    }
    

    Use the redirector like this:

    log.Fatal(http.ListenAndServeTLS(addr, certFile, keyFile, wwwRedirect(handler))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么