Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Last active October 31, 2018 08:35
Show Gist options
  • Save bgadrian/a3bec1f0afb34c4f399632fd18dccd16 to your computer and use it in GitHub Desktop.
Save bgadrian/a3bec1f0afb34c4f399632fd18dccd16 to your computer and use it in GitHub Desktop.
Secure simple web server in Go (general snippets)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
log.Println("shutting down signal received, waiting ...")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
srv.Shutdown(ctx)
os.Exit(0)
package server
import (
"crypto/tls"
"net/http"
"time"
)
func New(mux http.Handler, serverAddress string) *http.Server {
// See https://blog.cloudflare.com/exposing-go-on-the-internet/ for details
// about these settings
tlsConfig := &tls.Config{
// Causes servers to use Go's default cipher suite preferences,
// which are tuned to avoid attacks. Does nothing on clients.
PreferServerCipherSuites: true,
// Only use curves which have assembly implementations
CurvePreferences: []tls.CurveID{
tls.CurveP256,
tls.X25519, // Go 1.8 only
},
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
},
}
srv := &http.Server{
Addr: serverAddress,
ReadTimeout: 1 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 20 * time.Second,
TLSConfig: tlsConfig,
Handler: mux,
MaxHeaderBytes: 5 << 10, //5Kb, default is 1MB
}
return srv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment