-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
server.go
84 lines (70 loc) · 1.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
package httpserver
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"sync"
"time"
)
type TestServer struct {
*httptest.Server
mu sync.Mutex
routes map[string]Response
stats map[string]*Stat
}
func NewTestServer(routes map[string]Response) *TestServer {
ts := &TestServer{
routes: routes,
stats: map[string]*Stat{},
}
ts.Server = httptest.NewServer(ts)
return ts
}
func (s *TestServer) SetRoute(name string, resp Response) {
s.mu.Lock()
defer s.mu.Unlock()
s.routes[name] = resp
}
func (s *TestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
resp, ok := s.routes[r.URL.Path]
if !ok {
w.WriteHeader(http.StatusNotFound)
s.mu.Unlock()
return
}
if _, ok := s.stats[r.URL.Path]; !ok {
s.stats[r.URL.Path] = &Stat{}
}
s.stats[r.URL.Path].AllRequests++
if resp.LastModified != nil {
w.Header().Set("Last-Modified", resp.LastModified.Format(time.RFC850))
}
if resp.Etag != "" {
w.Header().Set("ETag", resp.Etag)
if match := r.Header.Get("If-None-Match"); match == resp.Etag {
w.WriteHeader(http.StatusNotModified)
s.stats[r.URL.Path].CachedRequests++
s.mu.Unlock()
return
}
}
s.mu.Unlock()
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(resp.Content))
}
func (s *TestServer) Stats(name string) (st Stat) {
if st, ok := s.stats[name]; ok {
return *st
}
return
}
type Response struct {
Content []byte
Etag string
LastModified *time.Time
}
type Stat struct {
AllRequests, CachedRequests int
}