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

Function httpRequest

pkg/cmd/api/http.go:16–93  ·  view source on GitHub ↗
(client *http.Client, hostname string, apiHost string, method string, p string, params any, headers []string)

Source from the content-addressed store, hash-verified

14)
15
16func httpRequest(client *http.Client, hostname string, apiHost string, method string, p string, params any, headers []string) (*http.Response, error) {
17 isGraphQL := p == "graphql"
18 var requestURL string
19 if strings.Contains(p, "://") {
20 // Absolute URLs are used as-is; api_host is never applied to them.
21 requestURL = p
22 } else if isGraphQL {
23 // First we determine the GQL endpoint for the canonical host, which depends on what type of host it is
24 // e.g github.com will be at https://api.github.com/graphql and GHES myghes.com will be at https://myghes.com/api/graphql.
25 requestURL = ghinstance.GraphQLEndpoint(hostname)
26 if apiHost != "" {
27 requestURL = swapURLHost(requestURL, apiHost)
28 }
29 } else {
30 // Note that the gh api command takes the path verbatim from the user, so we
31 // intentionally do not route it through safeurl and do not escape it here.
32 requestURL = ghinstance.RESTPrefix(hostname) + strings.TrimPrefix(p, "/")
33 if apiHost != "" {
34 requestURL = swapURLHost(requestURL, apiHost)
35 }
36 }
37
38 var body io.Reader
39 var bodyIsJSON bool
40
41 switch pp := params.(type) {
42 case map[string]any:
43 if strings.EqualFold(method, "GET") {
44 requestURL = addQuery(requestURL, pp)
45 } else {
46 if isGraphQL {
47 pp = groupGraphQLVariables(pp)
48 }
49 b, err := json.Marshal(pp)
50 if err != nil {
51 return nil, fmt.Errorf("error serializing parameters: %w", err)
52 }
53 body = bytes.NewBuffer(b)
54 bodyIsJSON = true
55 }
56 case io.Reader:
57 body = pp
58 case nil:
59 body = nil
60 default:
61 return nil, fmt.Errorf("unrecognized parameters type: %v", params)
62 }
63
64 req, err := http.NewRequest(strings.ToUpper(method), requestURL, body)
65 if err != nil {
66 return nil, err
67 }
68
69 for _, h := range headers {
70 idx := strings.IndexRune(h, ':')
71 if idx == -1 {
72 return nil, fmt.Errorf("header %q requires a value separated by ':'", h)
73 }

Callers 2

apiRunFunction · 0.85
Test_httpRequestFunction · 0.85

Calls 11

GraphQLEndpointFunction · 0.92
RESTPrefixFunction · 0.92
swapURLHostFunction · 0.85
addQueryFunction · 0.85
groupGraphQLVariablesFunction · 0.85
ContainsMethod · 0.80
ErrorfMethod · 0.65
AddMethod · 0.65
GetMethod · 0.65
SetMethod · 0.65
DoMethod · 0.65

Tested by 1

Test_httpRequestFunction · 0.68