-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
195 lines (163 loc) · 4.49 KB
/
server.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package rest
import (
"context"
"crypto/tls"
"fmt"
"github.com/go-chi/chi/v5"
"log"
"net/http"
"os"
"sync"
"sync/atomic"
"time"
)
type SSLConfig struct {
Port int // https server port
Redirect bool // defines if http requests will be redirected to the https
URL string // url where http requests will be redirected
CertPath string // path to the ssl certificate
KeyPath string // path to the ssl key
}
// Server - rest server struct
type Server struct {
Address string
Port int
IsReady *atomic.Value
SSL *SSLConfig
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
httpServer *http.Server
httpsServer *http.Server
mu sync.Mutex
}
// NewServer - will create new rest server on specified port
func NewServer(port int) *Server {
return &Server{
Port: port,
}
}
// Run - will initialize server and run it on provided port
func (s *Server) Run(router http.Handler) error {
if s.Address == "*" {
s.Address = ""
}
if s.Port == 0 {
s.Port = 8080
}
if s.IsReady == nil {
s.IsReady = &atomic.Value{}
s.IsReady.Store(true)
}
if s.ReadHeaderTimeout == 0 {
s.ReadHeaderTimeout = 10 * time.Second
}
if s.WriteTimeout == 0 {
s.WriteTimeout = 30 * time.Second
}
if s.IdleTimeout == 0 {
s.IdleTimeout = 60 * time.Second
}
if router == nil {
mux := chi.NewRouter()
mux.Use(Readiness("/readiness", s.IsReady))
mux.HandleFunc("/ping", okHandler)
mux.HandleFunc("/liveness", okHandler)
router = mux
}
log.Printf("[INFO] http rest server on %s:%d", s.Address, s.Port)
httpRouter := router
if s.SSL != nil {
if s.SSL.Port == 0 {
s.SSL.Port = s.Port + 1
}
if s.SSL.Redirect {
mux := chi.NewRouter()
mux.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
newURL := s.SSL.URL + r.URL.Path
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusTemporaryRedirect)
}))
httpRouter = mux
log.Printf("[INFO] http redirect server on %s:%d", s.Address, s.Port)
}
if _, err := os.Stat(s.SSL.CertPath); os.IsNotExist(err) {
return fmt.Errorf("ssl certificate not found: %s", s.SSL.CertPath)
}
if _, err := os.Stat(s.SSL.KeyPath); os.IsNotExist(err) {
return fmt.Errorf("ssl key not found: %s", s.SSL.KeyPath)
}
log.Printf("[INFO] https rest server on %s:%d", s.Address, s.SSL.Port)
s.mu.Lock()
s.httpsServer = s.https(s.Address, s.SSL.Port, router)
s.mu.Unlock()
go func() {
log.Printf("[WARN] https server terminated, %s", s.httpsServer.ListenAndServeTLS(s.SSL.CertPath, s.SSL.KeyPath))
}()
}
s.mu.Lock()
s.httpServer = s.http(s.Address, s.Port, httpRouter)
s.mu.Unlock()
if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("start http server, %s", err)
}
return nil
}
// Shutdown - shutdown rest server
func (s *Server) Shutdown() error {
log.Print("[INFO] shutdown rest server")
s.mu.Lock()
defer s.mu.Unlock()
if s.httpServer != nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
if err := s.httpServer.Shutdown(ctx); err != nil {
return err
}
}
if s.httpsServer != nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
if err := s.httpsServer.Shutdown(ctx); err != nil {
return err
}
}
return nil
}
func (s *Server) http(address string, port int, router http.Handler) *http.Server {
return &http.Server{
Addr: fmt.Sprintf("%s:%d", address, port),
Handler: router,
ReadHeaderTimeout: s.ReadHeaderTimeout,
WriteTimeout: s.WriteTimeout,
IdleTimeout: s.IdleTimeout,
}
}
func (s *Server) https(address string, port int, router http.Handler) *http.Server {
server := s.http(address, port, router)
server.TLSConfig = &tls.Config{
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,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
},
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{
tls.CurveP256,
tls.X25519,
tls.CurveP384,
},
}
return server
}
func okHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("."))
}