Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从https://www.*到https://*与golang library net/http_Go_Ssl_Redirect - Fatal编程技术网

如何从https://www.*到https://*与golang library net/http

如何从https://www.*到https://*与golang library net/http,go,ssl,redirect,Go,Ssl,Redirect,我正在尝试使用golang library net/http将所有请求重定向到同一url 目前正在工作: -> -> 尚未生效: -> 这两个URL为所有请求的资源返回相同的内容,但这对于会话cookie并不重要 我的最小代码: func listenAndHandle() { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

我正在尝试使用golang library 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进行处理。

使用重定向到裸域或委托给原始处理程序的处理程序包装TLS服务器处理程序

问题中的代码用作处理程序的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)))

尝试不使用
r.Host
,而只使用
r.URL.Host
?谢谢。当我尝试这一点时,我最初得到了所有请求的CORS错误,声明没有设置访问控制允许源。一次偶然的机会,我重新注册了我的服务人员,该服务人员缓存了我的大部分回复,目前它仍然有效。不幸的是,我不明白到底出了什么问题。