forked from mercadolibre/golang-restclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mockup.go
181 lines (146 loc) · 3.78 KB
/
mockup.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
package rest
import (
"errors"
"flag"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"sort"
"strings"
"sync"
)
const MOCK_NOT_FOUND_ERROR string = "MockUp nil!"
var mockUpEnv bool
var mockMap = make(map[string]*Mock)
var mockDbMutex sync.RWMutex
var mockServer *httptest.Server
var mux *http.ServeMux
var mockServerURL *url.URL
// Mock serves the purpose of creating Mockups.
// All requests will be sent to the mockup server if mockup is activated.
// To activate the mockup *environment* you have two ways: using the flag -mock
// go test -mock
//
// Or by programmatically starting the mockup server
// StartMockupServer()
type Mock struct {
// Request URL
URL string
// Request HTTP Method (GET, POST, PUT, PATCH, HEAD, DELETE, OPTIONS)
// As a good practice use the constants in http package (http.MethodGet, etc.)
HTTPMethod string
// Request array Headers
ReqHeaders http.Header
// Request Body, used with POST, PUT & PATCH
ReqBody string
// Response HTTP Code
RespHTTPCode int
// Response Array Headers
RespHeaders http.Header
// Response Body
RespBody string
}
// StartMockupServer sets the enviroment to send all client requests
// to the mockup server.
func StartMockupServer() {
mockUpEnv = true
if mockServer == nil {
startMockupServ()
}
}
// StopMockupServer stop sending requests to the mockup server
func StopMockupServer() {
mockUpEnv = false
mockServer.Close()
mockServer = nil
mockServerURL = nil
mux = nil
}
func startMockupServ() {
if mockUpEnv {
mux = http.NewServeMux()
mockServer = httptest.NewServer(mux)
mux.HandleFunc("/", mockupHandler)
mockDbMutex = *new(sync.RWMutex)
var err error
if mockServerURL, err = url.Parse(mockServer.URL); err != nil {
panic(err)
}
}
}
func init() {
flag.BoolVar(&mockUpEnv, "mock", false,
"Use 'mock' flag to tell package rest that you would like to use mockups.")
// 以下問題のためコメントアウト
// https://selfnote.work/20200327/programming/golang-testing2/
// flag.Parse()
startMockupServ()
}
// AddMockups ...
func AddMockups(mocks ...*Mock) error {
for _, m := range mocks {
normalizedUrl, err := getNormalizedUrl(m.URL)
if err != nil {
return errors.New(fmt.Sprintf("Error parsing mock with url=%s. Cause: %s", m.URL, err.Error()))
}
mockDbMutex.Lock()
mockMap[m.HTTPMethod+" "+normalizedUrl] = m
mockDbMutex.Unlock()
}
return nil
}
//check if a string url is valid and also sort query params in order to make the url easy to compare
func getNormalizedUrl(urlStr string) (string, error) {
urlObj, err := url.Parse(urlStr)
if err != nil {
return "", err
}
result := urlStr
//sorting query param strings
if len(urlObj.RawQuery) > 0 {
result = strings.Replace(urlStr, urlObj.RawQuery, "", 1)
mk := make([]string, len(urlObj.Query()))
i := 0
for k, _ := range urlObj.Query() {
mk[i] = k
i++
}
sort.Strings(mk)
for i := 0; i < len(mk); i++ {
if i+1 < len(mk) {
result = fmt.Sprintf("%s%s=%s&", result, mk[i], urlObj.Query().Get(mk[i]))
} else {
result = fmt.Sprintf("%s%s=%s", result, mk[i], urlObj.Query().Get(mk[i]))
}
}
}
return result, nil
}
// FlushMockups ...
func FlushMockups() {
mockDbMutex.Lock()
mockMap = make(map[string]*Mock)
mockDbMutex.Unlock()
}
func mockupHandler(writer http.ResponseWriter, req *http.Request) {
normalizedUrl, err := getNormalizedUrl(req.Header.Get("X-Original-URL"))
if err == nil {
mockDbMutex.RLock()
m := mockMap[req.Method+" "+normalizedUrl]
mockDbMutex.RUnlock()
if m != nil {
// Add headers
for k, v := range m.RespHeaders {
for _, vv := range v {
writer.Header().Add(k, vv)
}
}
writer.WriteHeader(m.RespHTTPCode)
writer.Write([]byte(m.RespBody))
return
}
}
writer.WriteHeader(http.StatusBadRequest)
writer.Write([]byte(MOCK_NOT_FOUND_ERROR))
}