-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
68 lines (61 loc) · 1.62 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
package main
import (
"fmt"
"net/http"
"strings"
"time"
)
type server struct {
mux mux
log logger
client *http.Client
}
func useStdLibOptions() func(*server) error {
return func(s *server) error {
s.mux = http.NewServeMux()
s.log = newStdLogger()
s.client = &http.Client{Timeout: 30 * time.Second}
return nil
}
}
// newServer allocates and returns a new server.
func newServer(options ...func(*server) error) (*server, error) {
s := &server{}
for _, o := range options {
if err := o(s); err != nil {
return nil, err
}
}
if s.mux == nil {
return nil, fmt.Errorf("must provide an option func that specifies a mux")
}
if s.log == nil {
return nil, fmt.Errorf("must provide an option func that specifies a logger")
}
if s.client == nil {
return nil, fmt.Errorf("must provide an option func that specifies an *http.Client")
}
s.init()
return s, nil
}
// init sets up a server by performing tasks like mapping
// path endpoints to handler functions.
func (s *server) init() {
s.mux.HandleFunc("/healthz", s.handleHealthz)
}
func (s *server) handleHealthz(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "ok")
}
// ServeHTTP satisfies the http.Handler interface. It will compress all
// responses if the appropriate request headers are set.
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
s.mux.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gzw := newGzipResponseWriter(w)
defer gzw.Close()
s.mux.ServeHTTP(gzw, r)
}