This repository has been archived by the owner on Nov 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
transports.go
67 lines (55 loc) · 1.53 KB
/
transports.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"time"
"golang.org/x/crypto/acme/autocert"
)
func StartServer(c *config, s *http.Server) error {
s.Addr = fmt.Sprintf(fmt.Sprintf(":%s", c.Port))
if !c.TLS {
return s.ListenAndServe()
}
certCache := "/tmp/certs"
key, cert := "", ""
// LetsEncrypt is good. Thanks LetsEncrypt.
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(cfg.UrlRoot),
Cache: autocert.DirCache(certCache),
}
// Attempt to boot a port 80 https redirect
go func() { HttpsRedirect() }()
s.TLSConfig = &tls.Config{
GetCertificate: certManager.GetCertificate,
// Causes servers to use Go's default ciphersuite 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,
},
}
return s.ListenAndServeTLS(cert, key)
}
// Redirect HTTP to https if port 80 is open
func HttpsRedirect() {
ln, err := net.Listen("tcp", ":80")
if err != nil {
return
}
log.Info("TCP Port 80 is available, redirecting traffic to https")
srv := &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Connection", "close")
url := "https://" + req.Host + req.URL.String()
http.Redirect(w, req, url, http.StatusMovedPermanently)
}),
}
log.Fatal(srv.Serve(ln))
}