【问题标题】:Autocert using gorilla mux使用 gorilla mux 进行自动认证
【发布时间】:2019-02-26 17:26:13
【问题描述】:

我想使用 autocert 和 gorila mux 生成证书,我的实际代码是:

func main() {
    certManager := autocert.Manager{
        Prompt:     autocert.AcceptTOS,
        //HostPolicy: autocert.HostWhitelist("example.com"),
        Cache:      autocert.DirCache("./certs"),            //Folder for storing certificates
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello world"))
    })

    server := &http.Server{
        Addr:      ":https",
        TLSConfig: &tls.Config{
            GetCertificate: certManager.GetCertificate,
        },
    }

    go http.ListenAndServe(":http", certManager.HTTPHandler(nil))

    log.Fatal(server.ListenAndServeTLS("", "")) //Key and cert are coming from Let's Encrypt
}

我的路由器是:

r := mux.NewRouter()
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
r.HandleFunc("/login.html",  LoginHtml)

如何将 gurilla mux 集成到我的实际代码中?

【问题讨论】:

标签: go


【解决方案1】:

集成是这样的:

func main() {
    certManager := autocert.Manager{
        Prompt:     autocert.AcceptTOS,
        //HostPolicy: autocert.HostWhitelist("example.com"),
        Cache:      autocert.DirCache("./certs"),            //Folder for storing certificates
    }

    r := mux.NewRouter()
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
    r.HandleFunc("/login.html",  LoginHtml)

    server := &http.Server{
        Addr:      ":https",
        Handler:   r,
        TLSConfig: &tls.Config{
            GetCertificate: certManager.GetCertificate,
        },
    }

    go http.ListenAndServe(":http", certManager.HTTPHandler(nil))

    log.Fatal(server.ListenAndServeTLS("", "")) //Key and cert are coming from Let's Encrypt
}

我建议为服务器添加一些超时。我通常选择 Read、Write 和 Idle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2014-12-22
    • 2017-06-19
    • 2014-11-30
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多