Golang Tutorial: Create HTTPS Server use net/http

It is simple to craete a HTTPS Server use net/http, see code below:

package main

import (
	"net/http"
	"fmt"
)

type SimpleHandler struct {
	Name string
}

func (h *SimpleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s: Hello World!", h.Name)
}

func main() {
	server := http.Server{
		Addr:    "127.0.0.1:8080",
		Handler: &SimpleHandler{Name: "SimpleServer"},
	}
	server.ListenAndServeTLS("cert.pem", "key.pem")
}

We can use golang’s crypto libraries to create SSL certificates that used in simple https server above. see code below:

package main

import (
	"crypto/rand"
	"crypto/x509/pkix"
	"math/big"
	"crypto/x509"
	"encoding/pem"
	"net"
	"os"
	"time"
	"crypto/rsa"
)

const (
	certFileName = "cert.pem"
	keyFileName  = "key.pem"
)

func main() {
	max := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, _ := rand.Int(rand.Reader, max)
	subject := pkix.Name{
		Organization:       []string{"Manning Publications Co."},
		OrganizationalUnit: []string{"Books"},
		CommonName:         "Go Web Programming",
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject:      subject,
		NotBefore:    time.Now(),
		NotAfter:     time.Now().Add(365 * 24 * time.Hour),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		IPAddresses:  []net.IP{net.ParseIP("127.0.0.1")},
	}

	pk, _ := rsa.GenerateKey(rand.Reader, 2048)

	derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &pk.PublicKey, pk)
	certOut, _ := os.Create(certFileName)
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()

	keyOut, _ := os.Create(keyFileName)
	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)})
	keyOut.Close()
}

(Note: This article’s code is reference from the simple code in book <Go Web Programming> and this link is My Code repository)

 拯救者 Golang Tutorial: What's DefaultServeMux in net/http 

Comments

©2015-2021 Alimy All rights reserved.