-
Notifications
You must be signed in to change notification settings - Fork 22
/
server.go
188 lines (158 loc) · 4.8 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
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
182
183
184
185
186
187
188
package mock
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"github.com/gorilla/mux"
)
// EndpointPattern models the GitHub's API endpoints
type EndpointPattern struct {
Pattern string // eg. "/repos/{owner}/{repo}/actions/artifacts"
Method string // "GET", "POST", "PATCH", etc
}
// MockBackendOption is used to configure the *mux.router
// for the mocked backend
type MockBackendOption func(*mux.Router)
// FIFOReponseHandler handler implementation that
// responds to the HTTP requests following a FIFO approach.
//
// Once all available `Responses` have been used, this handler will panic()!
type FIFOReponseHandler struct {
lock sync.Mutex
Responses [][]byte
CurrentIndex int
}
// ServeHTTP implementation of `http.Handler`
func (srh *FIFOReponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
srh.lock.Lock()
defer srh.lock.Unlock()
if srh.CurrentIndex > len(srh.Responses) {
panic(fmt.Sprintf(
"go-github-mock: no more mocks available for %s",
r.URL.Path,
))
}
defer func() {
srh.CurrentIndex++
}()
w.Write(srh.Responses[srh.CurrentIndex])
}
// PaginatedReponseHandler handler implementation that
// responds to the HTTP requests and honors the pagination headers
//
// Header e.g: `Link: <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=15>; rel="next",
// <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last",
// <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=1>; rel="first",
// <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=13>; rel="prev"`
//
// See: https://docs.github.com/en/rest/guides/traversing-with-pagination
type PaginatedReponseHandler struct {
ResponsePages [][]byte
}
func (prh *PaginatedReponseHandler) getCurrentPage(r *http.Request) int {
strPage := r.URL.Query().Get("page")
if strPage == "" {
return 1
}
page, err := strconv.Atoi(r.URL.Query().Get("page"))
if err == nil {
return page
}
// this should never happen as the request is being made by the SDK
panic(fmt.Sprintf("invalid page: %s", strPage))
}
func (prh *PaginatedReponseHandler) generateLinkHeader(
w http.ResponseWriter,
r *http.Request,
) {
currentPage := prh.getCurrentPage(r)
lastPage := len(prh.ResponsePages)
buf := bytes.NewBufferString(`<?page=1>; rel="first",`)
buf.WriteString(fmt.Sprintf(`<?page=%d>; rel="last",`, lastPage))
if currentPage < lastPage {
// when resp.NextPage == 0, it means no more pages
// which is basically as not setting it in the response
buf.WriteString(fmt.Sprintf(`<?page=%d>; rel="next",`, currentPage+1))
}
if currentPage > 1 {
buf.WriteString(fmt.Sprintf(`<?page=%d>; rel="prev",`, currentPage-1))
}
w.Header().Add("Link", buf.String())
}
// ServeHTTP implementation of `http.Handler`
func (prh *PaginatedReponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
prh.generateLinkHeader(w, r)
w.Write(prh.ResponsePages[prh.getCurrentPage(r)-1])
}
// EnforceHostRoundTripper rewrites all requests with the given `Host`.
type EnforceHostRoundTripper struct {
Host string
UpstreamRoundTripper http.RoundTripper
}
// RoundTrip implementation of `http.RoundTripper`
func (efrt *EnforceHostRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
splitHost := strings.Split(efrt.Host, "://")
r.URL.Scheme = splitHost[0]
r.URL.Host = splitHost[1]
return efrt.UpstreamRoundTripper.RoundTrip(r)
}
// NewMockedHTTPClient creates and configures an http.Client that points to
// a mocked GitHub's backend API.
//
// Example:
//
// mockedHTTPClient := NewMockedHTTPClient(
// WithRequestMatch(
// GetUsersByUsername,
// github.User{
// Name: github.String("foobar"),
// },
// ),
// WithRequestMatch(
// GetUsersOrgsByUsername,
// []github.Organization{
// {
// Name: github.String("foobar123thisorgwasmocked"),
// },
// },
// ),
// WithRequestMatchHandler(
// GetOrgsProjectsByOrg,
// func(w http.ResponseWriter, _ *http.Request) {
// w.Write(MustMarshal([]github.Project{
// {
// Name: github.String("mocked-proj-1"),
// },
// {
// Name: github.String("mocked-proj-2"),
// },
// }))
// },
// ),
// )
//
// c := github.NewClient(mockedHTTPClient)
func NewMockedHTTPClient(options ...MockBackendOption) *http.Client {
router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
WriteError(
w,
http.StatusNotFound,
fmt.Sprintf("mock response not found for %s", r.URL.Path),
)
})
for _, o := range options {
o(router)
}
mockServer := httptest.NewServer(router)
c := mockServer.Client()
c.Transport = &EnforceHostRoundTripper{
Host: mockServer.URL,
UpstreamRoundTripper: mockServer.Client().Transport,
}
return c
}