Gorilla mux使用自动证书

3

我想使用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集成到我的现有代码中?

1
server.Handler = r - Charlie Tumahai
1个回答

3
集成过程如下:
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
}

我建议在服务器上添加一些超时时间。通常我会设置读取、写入和空闲的超时时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接