如何使用 golang 库 net/http 从 https://www.*

我正在尝试使用 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 下正常工作。


慕妹3146593
浏览 167回答 1
1回答

小唯快跑啊

使用重定向到裸域或委托给原始处理程序的处理程序包装 TLS 服务器处理程序。问题中的代码使用http.DefaultServeMux作为处理程序的 TLS 服务器。这是一个处理函数,可以重定向或调用 http.DefaultServeMux:func redirectWWW(w http.ResponseWriter, r *http.Request) {    if strings.HasPrefix(r.Host, "www.") {        u := *r.URL        u.Scheme = "https"        u.Host = strings.TrimPrefix(r.Host, "www.")        http.Redirect(w, r, u.String(), http.StatusFound)        return    }    http.DefaultServeMux.ServeHTTP(w, r)}在 TLS 服务器中使用此处理程序:    handle.Lv.Println(http.ListenAndServeTLS(database.Config.PORT, database.Config.TLScertfile,database.Config.TLSkeyfile, http.HandlerFunc(redirectWWW)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go