Created
April 11, 2018 01:45
-
-
Save tehmoon/507f331abb6357dfeedd33356f4baca1 to your computer and use it in GitHub Desktop.
Simple https server in go with self-signed certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"fmt" | |
"io" | |
"os" | |
"log" | |
"crypto/x509" | |
"crypto/x509/pkix" | |
"net" | |
"crypto/rsa" | |
"math/big" | |
"time" | |
"crypto/tls" | |
cryptoRand "crypto/rand" | |
) | |
func genCertificate() (*tls.Certificate, error) { | |
now := time.Now() | |
subject := pkix.Name{ | |
CommonName: "*", | |
} | |
tpl := &x509.Certificate{ | |
NotBefore: now, | |
NotAfter: now.Add(24 * 365 * time.Hour), | |
SerialNumber: new(big.Int).SetInt64(1), | |
Subject: subject, | |
} | |
key, err := rsa.GenerateKey(cryptoRand.Reader, 4096) | |
if err != nil { | |
return nil, err | |
} | |
x509Cert, err := x509.CreateCertificate(cryptoRand.Reader, tpl, tpl, key.Public(), key) | |
if err != nil { | |
return nil, err | |
} | |
certificate := &tls.Certificate{ | |
Certificate: [][]byte{x509Cert,}, | |
PrivateKey: key, | |
} | |
return certificate, err | |
} | |
func main() { | |
cert, err := genCertificate() | |
if err != nil { | |
log.Fatal(err) | |
} | |
tlsConfig := &tls.Config{ | |
Certificates: []tls.Certificate{*cert,}, | |
} | |
http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) { | |
log.Println("new conn") | |
io.Copy(os.Stdout, r.Body) | |
r.Body.Close() | |
fmt.Println() | |
}) | |
laddr := &net.TCPAddr{ | |
IP: net.ParseIP("0.0.0.0"), | |
Port: 12346, | |
} | |
l, err := net.ListenTCP("tcp", laddr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
tlsListener := tls.NewListener(l, tlsConfig) | |
log.Fatal(http.Serve(tlsListener, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment