forked from saltbo/gopkg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
65 lines (52 loc) · 1.06 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
package testutil
import (
"log"
"net/http"
"net/http/httptest"
"net/url"
"time"
)
type mockServer struct {
*httptest.Server
req *http.Request
host string
duration time.Duration
respBody []byte
}
func NewMockServer() *mockServer {
ms := new(mockServer)
ms.Server = httptest.NewServer(ms)
ms.host = ms.URL().Host
ms.respBody = []byte("mock succ!")
return ms
}
func (m *mockServer) SetHost(host string) {
m.host = host
}
func (m *mockServer) SetDuration(d time.Duration) {
m.duration = d
}
func (m *mockServer) SetResponseBody(body []byte) {
m.respBody = body
}
func (m *mockServer) URL() *url.URL {
u, _ := url.Parse(m.Server.URL)
return u
}
func (m *mockServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Host != m.host {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
m.req = r
if m.duration > 0 {
time.Sleep(m.duration)
}
for _, cookie := range r.Cookies() {
http.SetCookie(w, cookie)
}
if _, err := w.Write(m.respBody); err != nil {
log.Printf("[mockServer] response failed: %s", err)
return
}
}