生成ssl证书

openssl genrsa -out server.key 2048
openssl req -new -x509 -key server.key -out server.pem -days 365

结合ServeMux创建https服务器

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
)

func index(w http.ResponseWriter, r *http.Request) {
    // 多路复用的路由处理很奇怪,具体情况为:
    // 请求相应path会进入到ServeMux绑定的handler
    // 请求不存在的path,却会进到绑定到/的handler,故这里做一层处理
    if r.RequestURI != "/" {
        w.WriteHeader(404)
        return
    }
    fmt.Fprintf(w, "%s\n", "Hello Wrold!")
    fmt.Fprintf(w, "You are in the index\n")
}

func login(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "You are in the login\n")
}

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/", index)
    mux.HandleFunc("/login", login)

    // 读取证书文件
    cert, err := tls.LoadX509KeyPair("./server.pem", "./server.key")
    if err != nil {
        fmt.Println(err)
        return
    }

    server := &http.Server{
        Addr:    "0.0.0.0:9090",
        Handler: mux,
        // 配置tls
        TLSConfig: &tls.Config{
            Certificates: []tls.Certificate{ cert },
        },
    }

    server.ListenAndServeTLS("", "")
}

常见错误

证书不受信任,例如本文自己生成的证书:

http: TLS handshake error from ip:port: remote error: tls: unknown certificate

客户端拒绝请求不受信任证书的地址:

http: TLS handshake error from ip:port: EOF

参考文档

使用Go实现TLS 服务器和客户端
Golang创建最简单的HTTP和HTTPS服务
Go代码打通HTTPs
使用 Go 编程语言生成自授权 TLS 证书

Last modification:October 28, 2019
If you think my article is useful to you, please feel free to appreciate