英文:
How to route https request before ListenAndServeTLS
问题
在确定要使用哪些证书文件之前,我需要检查请求的主机地址。如何做到这一点?
我不能调用
http.ListenAndServeTLS(":443", "cerfile", "certkey", mux)
因为证书文件和要使用的 mux
取决于请求的主机地址,而该地址仅在处理程序中可用!
当然,我应该只使用 443 端口!
这可以仅使用 http
包来完成吗?
英文:
Before I know which certificate files to use, I need to check the request Host, how to do that ?
I can't call
http.ListenAndServeTLS(":443", "cerfile", "certkey", mux)
because the cert files and "mux" to use depends on the request host address, which is only available in the handler!
and of course I should only use the 443 port!
Can this be done with http package alone ?
答案1
得分: 1
根据Burak Serdar的评论,你可以自定义tls.Config
的GetCertificate
方法来根据不同的主机返回特定的证书。
示例代码:
mux := http.NewServeMux()
cfg := &tls.Config{
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
// 根据info.ServerName获取证书
},
}
srv := &http.Server{
Addr: ":443",
Handler: mux,
TLSConfig: cfg,
}
fmt.Println(srv.ListenAndServeTLS("defaulttls.crt", "defaulttls.key"))
关于如何通过ClientHelloInfo
获取证书,你可以参考autocert示例代码。
英文:
As Burak Serdar comment, you could custom GetCertificate
of tls.Config
to return the specific certificate by different host.
Sample Code
mux := http.NewServeMux()
cfg := &tls.Config{
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
// get certificate by info.ServerName
},
}
srv := &http.Server{
Addr: ":443",
Handler: mux,
TLSConfig: cfg,
}
fmt.Println(srv.ListenAndServeTLS("defaulttls.crt", "defaulttls.key"))
About how to get a certificate by ClientHelloInfo
, you could refer to autocert sample codes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论