如何在Go中重写/重定向从http到https?

Ale*_*lex 16 go

我已经提出了TLS并且它有效.我知道如何在nginx中从http重写为https,但我不再使用nginx了.我不知道如何在Go中正确地做到这一点.

func main() {

    certificate := "/srv/ssl/ssl-bundle.crt"
    privateKey := "/srv/ssl/mykey.key"

    http.HandleFunc("/", rootHander)
    // log.Fatal(http.ListenAndServe(":80", nil))
    log.Fatal(http.ListenAndServeTLS(":443", certificate, privateKey, nil))
}

func rootHander(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("To the moon!"))
}
Run Code Online (Sandbox Code Playgroud)

我怎么能以这种方式做到这一点?

khr*_*hrm 14

创建一个处理重定向到https的处理程序,如:

func redirectTLS(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "https://IPAddr:443"+r.RequestURI, http.StatusMovedPermanently)
}
Run Code Online (Sandbox Code Playgroud)

然后重定向http流量:

go func() {
    if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil {
        log.Fatalf("ListenAndServe error: %v", err)
    }
}()
Run Code Online (Sandbox Code Playgroud)

  • 对于要重定向到的地址,最好使用"https://"+ r.Host + r.RequestURI`,这样可以避免硬编码主机名或IP地址. (4认同)

jab*_*cky 6

上面发布的解决方案有点不灵活,特别是如果外部主机名与本地主机不同。

这是我用于 HTTP->HTTPS 重定向的代码:

package main

import (
    "net"
    "log"
    "net/http"
)

var httpAddr ":8080"
var httpsAddr ":8443"

func main() {
    srv := http.Server{
        Addr: httpsAddr,
    }

    _, tlsPort, err := net.SplitHostPort(httpsAddr)
    if err != nil {
        return err
    }
    go redirectToHTTPS(tlsPort)

    srv.ListenAndServeTLS("cert.pem", "key.pem")
}

func redirectToHTTPS(tlsPort string) {
    httpSrv := http.Server{
        Addr: httpAddr,
        Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
            host, _, _ := net.SplitHostPort(r.Host)
            u := r.URL
            u.Host = net.JoinHostPort(host, tlsPort)
            u.Scheme="https"
            log.Println(u.String())
            http.Redirect(w,r,u.String(), http.StatusMovedPermanently)
        }),
    }
    log.Println(httpSrv.ListenAndServe())
}
Run Code Online (Sandbox Code Playgroud)

如果您使用标准端口 (80,443),则不需要拆分连接地址,只需在 URL 上设置方案就足够了。