Golang HTTPS Server 撰寫方式

server.ListenAndServerTLS 需要兩個參數:The certFile and keyFile,此兩檔案需要Local的PEM encoded format for certificate and private key。

範例

package main

import (
    "crypto/tls"
    "crypto/x509"
    "encoding/pem"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// Credits for server code: https://gist.github.com/denji/12b3a568f092ab951456

func main() {
    cert := "/path/to/cert.pem"
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
        w.Write([]byte("It works !!\n"))
    })

    b, _ := ioutil.ReadFile(cert)
    var pemBlocks []*pem.Block
    var v *pem.Block
    var pkey []byte

    for {
        v, b = pem.Decode(b)
        if v == nil {
            break
        }
        if v.Type == "RSA PRIVATE KEY" {
            pkey = pem.EncodeToMemory(v)
        } else {
            pemBlocks = append(pemBlocks, v)
        }
    }
    c, _ := tls.X509KeyPair(pem.EncodeToMemory(pemBlocks[0]), pkey)

    cfg := &tls.Config{
        MinVersion:               tls.VersionTLS12,
        CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
        PreferServerCipherSuites: true,
        CipherSuites: []uint16{
            tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
            tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
            tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
            tls.TLS_RSA_WITH_AES_256_CBC_SHA,
        },
        Certificates: []tls.Certificate{c},
    }
    srv := &http.Server{
        Addr:         ":9000",
        Handler:      mux,
        TLSConfig:    cfg,
        TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
    }

    log.Fatal(srv.ListenAndServeTLS("", ""))
}

參考資訊