-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
110 lines (91 loc) · 2.31 KB
/
http.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"crypto/tls"
"log"
"net"
"net/http"
"os"
"time"
)
func NewServer(addr string, handler http.Handler) *Server {
return &Server{&http.Server{
Addr: addr,
Handler: handler,
// https://blog.cloudflare.com/exposing-go-on-the-internet/
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
TLSConfig: &tls.Config{
NextProtos: []string{"h2", "http/1.1"},
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP256, tls.X25519},
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,
},
PreferServerCipherSuites: true,
},
}}
}
func NewServerTLS(addr string, cert tls.Certificate, handler http.Handler) *Server {
srv := NewServer(addr, handler)
srv.TLSConfig.Certificates = []tls.Certificate{cert}
return srv
}
type Server struct {
*http.Server
}
func (srv *Server) IsTLS() bool {
return len(srv.TLSConfig.Certificates) > 0 || srv.TLSConfig.GetCertificate != nil
}
func (srv *Server) Listen() (net.Listener, error) {
return net.Listen("tcp", srv.Addr)
}
func (srv *Server) ListenAndServe() error {
ln, err := srv.Listen()
if err != nil {
return err
}
return srv.Serve(ln)
}
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
ln, err := srv.Listen()
if err != nil {
return err
}
return srv.ServeTLS(ln, certFile, keyFile)
}
func (srv *Server) Start() error {
ln, err := srv.Listen()
if err != nil {
return err
}
if srv.IsTLS() {
ln = tls.NewListener(ln, srv.TLSConfig)
}
return srv.Serve(ln)
}
func HttpExample() {
addr := os.Getenv("HTTP_LISTEN")
if addr == "" {
addr = ":8080"
}
// use something like chi here
r := http.NewServeMux()
// certFile := "" // todo
// keyFile := "" // todo
// cert, err := tls.LoadX509KeyPair(certFile, keyFile)
// if err != nil {
// log.Fatalf("error loading certificate: %v", err)
// }
// server := NewServerTLS(addr, cert, r)
server := NewServer(addr, r)
serveErr := server.Start()
if serveErr != nil {
log.Printf("error starting http server: %v", serveErr)
}
}