MCPcopy Create free account
hub / github.com/cli/cli / ServeHTTP

Method ServeHTTP

script/ghmock/server.go:131–262  ·  view source on GitHub ↗
(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

129}
130
131func (m *mockServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
132 if r.Method == http.MethodConnect {
133 if m.ca != nil {
134 m.tunnel(w, r)
135 return
136 }
137 // Without ghmock's authority, a tunnel would reach a real host.
138 m.record(loggedRequest{Method: r.Method, Host: r.Host, Status: http.StatusForbidden, Blocked: true})
139 http.Error(w, "ghmock: HTTPS tunnels are blocked", http.StatusForbidden)
140 return
141 }
142 m.mu.Lock()
143 if m.closing {
144 m.mu.Unlock()
145 http.Error(w, "ghmock: server is closing", http.StatusServiceUnavailable)
146 return
147 }
148 m.handlers.Add(1)
149 m.mu.Unlock()
150 defer m.handlers.Done()
151
152 host := r.URL.Host
153 if host == "" {
154 host = r.Host
155 }
156 hostname := host
157 if h, _, err := net.SplitHostPort(host); err == nil {
158 hostname = h
159 }
160
161 entry := loggedRequest{Time: time.Now().UTC(), Method: r.Method, Host: hostname, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
162 if m.ca == nil && !isMockHost(hostname) {
163 entry.Status = http.StatusForbidden
164 entry.Blocked = true
165 m.record(entry)
166 http.Error(w, "ghmock: only "+mockHost+" is served", http.StatusForbidden)
167 return
168 }
169 if m.serveGitHTTP(w, r, entry) {
170 return
171 }
172
173 body, err := io.ReadAll(io.LimitReader(r.Body, maxRequestBody+1))
174 if err != nil {
175 entry.Status = http.StatusBadRequest
176 m.record(entry)
177 writeJSON(w, http.StatusBadRequest, map[string]string{"message": "ghmock: reading request body: " + err.Error()})
178 return
179 }
180 if len(body) > maxRequestBody {
181 entry.Status = http.StatusRequestEntityTooLarge
182 m.record(entry)
183 writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"message": "ghmock: request body exceeds 10 MiB"})
184 return
185 }
186 name, gql := requestName(r.Method, hostname, r.URL.Path, body)
187 entry.Name = name
188 entry.GraphQL = gql

Callers 1

recordingHandlerFunction · 0.45

Calls 15

tunnelMethod · 0.95
recordMethod · 0.95
serveGitHTTPMethod · 0.95
checkMethod · 0.95
graphQLSchemaMethod · 0.95
isMockHostFunction · 0.85
writeJSONFunction · 0.85
requestNameFunction · 0.85
missingResponseFunction · 0.85
responseHasBodyFunction · 0.85
trimGraphQLFunction · 0.85
ValidMethod · 0.80

Tested by

no test coverage detected