-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
73 lines (63 loc) · 1.7 KB
/
server.go
File metadata and controls
73 lines (63 loc) · 1.7 KB
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
package hex
import (
"net/http"
"net/http/httptest"
)
// Server wraps around (embeds) an httptest.Server, and also embeds an Expecter for making expectations
// The simplest way of using hex is to use NewServer or NewTLSServer.
type Server struct {
*httptest.Server
handler http.Handler
t TestingT
Expecter
}
// NewServer returns a new hex.Server object, wrapping an httptest.Server.
// Its first argument should be a testing.T, used to report failures.
// Its second argument is an http.Handler that may be nil.
func NewServer(t TestingT, handler http.Handler) *Server {
t.Helper()
s := Server{
t: t,
handler: handler,
}
s.Server = httptest.NewServer(&s)
s.URL = s.Server.URL
t.Cleanup(func() {
t.Helper()
s.HexReport(t)
})
return &s
}
// NewTLSServer returns a new hex.Server object, wrapping na httptest.Server created via NewTLSServer
// Its first argument should be a testing.T, used to report failures.
// Its second argument is an http.Handler that may be nil.
func NewTLSServer(t TestingT, handler http.Handler) *Server {
t.Helper()
s := Server{
t: t,
handler: handler,
}
s.Server = httptest.NewTLSServer(&s)
s.URL = s.Server.URL
t.Cleanup(func() {
t.Helper()
s.HexReport(t)
})
x := new(string)
*x = "foobar"
return &s
}
// ServeHTTP logs requests that come through the server so they can be matched against expectations, and
// evalutes any mock responses defined for matched expectations.
func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
exp := s.LogReq(req)
if exp != nil && exp.handler != nil {
exp.handler.ServeHTTP(rw, req)
if exp.callThrough == false {
return
}
}
if s.handler != nil {
s.handler.ServeHTTP(rw, req)
}
}