Created
April 13, 2018 18:57
-
-
Save tjamet/c9a53127c9bec54f62ed94685de85875 to your computer and use it in GitHub Desktop.
TLS HTTP server using in-memory 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
// From https://github.com/golang/go/blob/c0547476f342665514904cf2581a62135d2366c3/src/net/http/server.go#L3223 | |
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted | |
// connections. It's used by ListenAndServe and ListenAndServeTLS so | |
// dead TCP connections (e.g. closing laptop mid-download) eventually | |
// go away. | |
type tcpKeepAliveListener struct { | |
*net.TCPListener | |
} | |
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { | |
tc, err := ln.AcceptTCP() | |
if err != nil { | |
return | |
} | |
tc.SetKeepAlive(true) | |
tc.SetKeepAlivePeriod(3 * time.Minute) | |
return tc, nil | |
} | |
// ListenAndServeTLSKeyPair start a server using in-memory TLS KeyPair | |
func ListenAndServeTLSKeyPair(addr string, cert tls.Certificate, handler http.Handler) error { | |
// as defined in https://github.com/golang/go/blob/c0547476f342665514904cf2581a62135d2366c3/src/net/http/server.go#L3034 | |
if addr == "" { | |
addr = ":https" | |
} | |
// as defined in https://github.com/golang/go/blob/c0547476f342665514904cf2581a62135d2366c3/src/net/http/server.go#L3037 | |
ln, err := net.Listen("tcp", addr) | |
if err != nil { | |
return err | |
} | |
server := &http.Server{ | |
Addr: addr, | |
Handler: handler, | |
TLSConfig: &tls.Config{ | |
// alternatifely we can use GetCertificate func(*ClientHelloInfo) (*Certificate, error) | |
// for host-dependant certificates (possibly let's encrypt) | |
Certificates: []tls.Certificate{cert}, | |
}, | |
} | |
// if TLS config is defined, and no actual key path is provided, ServeTLS keeps the certificate | |
// https://github.com/golang/go/blob/c0547476f342665514904cf2581a62135d2366c3/src/net/http/server.go#L2832 | |
return server.ServeTLS(ln, "", "") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment