如何在Go中重写/重定向从http到https? [英] How do I rewrite / redirect from http to https in Go?

查看:311
本文介绍了如何在Go中重写/重定向从http到https?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了TLS并且它可以工作。我知道如何在http上重写nginx中的https,但我不再使用nginx。

  func main(){

我不知道如何在Go中做到这一点。证书:=/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!))
}

我会如何做到这一点?



  func redirectTLS(

)创建一个处理重定向到https的处理程序。 w http.ResponseWriter,r * http.Request){
http.Redirect(w,r,https:// IPAddr:443+ r.RequestURI,http.StatusMovedPermanently)
}

然后重定向http流量:

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


I have put up TLS and it works. I know how to rewrite from http to https in nginx, but I do not use nginx anymore. I don't know how to do this in Go properly.

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!"))
}

How would I do this in a good way?

解决方案

Create a handler which handles redirection to https like:

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

Then redirect http traffic:

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

这篇关于如何在Go中重写/重定向从http到https?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆