I have multiple domain (let's say abc.com and xyz.org) with diffrent certificate. Is it possible to use key and certificate based on hostname without going deep low level and net.Listen, etc. Just using simple http.ListenAndServeTLS(...) or similar ? Basically like what nginx does.
1条回答 默认 最新
- doulu8847 2016-02-26 02:23关注
BuildNameToCertificate() will sniff the hostname from the cert. If none match the SNI info it serves the [0]. https://golang.org/src/crypto/tls/common.go?s=18204:18245#L947
package main import ( "crypto/tls" "net/http" "time" "log" ) func myHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("tls")) } func main() { t := log.Logger{} var err error tlsConfig := &tls.Config{} tlsConfig.Certificates = make([]tls.Certificate, 3) // go http server treats the 0'th key as a default fallback key tlsConfig.Certificates[0], err = tls.LoadX509KeyPair("test0.pem", "key.pem") if err != nil { t.Fatal(err) } tlsConfig.Certificates[1], err = tls.LoadX509KeyPair("test1.pem", "key.pem") if err != nil { t.Fatal(err) } tlsConfig.Certificates[2], err = tls.LoadX509KeyPair("test2.pem", "key.pem") if err != nil { t.Fatal(err) } tlsConfig.BuildNameToCertificate() http.HandleFunc("/", myHandler) server := &http.Server{ ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, TLSConfig: tlsConfig, } listener, err := tls.Listen("tcp", ":8443", tlsConfig) if err != nil { t.Fatal(err) } log.Fatal(server.Serve(listener)) }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 PADS Logic 原理图
- ¥15 PADS Logic 图标
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
- ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
- ¥15 机器人轨迹规划相关问题