如何在 ListenAndServeTLS 之前路由 HTTPS 请求

huangapple go评论78阅读模式
英文:

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.ConfigGetCertificate方法来根据不同的主机返回特定的证书。

示例代码:

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

huangapple
  • 本文由 发表于 2022年10月28日 22:42:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/74237038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定