普通网友 2016-05-31 02:38
浏览 265
已采纳

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

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?

  • 写回答

3条回答 默认 最新

  • dongzen2675 2016-05-31 04:56
    关注

    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)
        }
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置