我正在尝试使用 golang 库 net/http 将所有请求重定向到相同的 url。
正在工作:
还没有工作:
两个 url 为所有请求的资源返回相同的内容,但这对于会话 cookie 无关紧要。
我的最小代码:
func listenAndHandle() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", handle.PageIndex)
go func() {
if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil {
handle.Lv.Println("ListenAndServe error:", err)
}
}()
handle.Lv.Println(http.ListenAndServeTLS(database.Config.PORT, database.Config.TLScertfile,
database.Config.TLSkeyfile, nil))
}
func redirectTLS(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Host, "www.") {
u := *r.URL
u.Host = strings.Replace(r.Host, "www.", "", 1)
u.Scheme = "https"
http.Redirect(w, r, u.String(), http.StatusFound)
return
}
http.Redirect(w, r, database.Config.TLSurl+r.RequestURI, http.StatusMovedPermanently)
}
我对添加另一个库来解决这个问题并不感兴趣,其他一切都可以在 golang 默认 net/http 下正常工作。
小唯快跑啊
相关分类