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

Function httpRequest

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

Source from the content-addressed store, hash-verified

14)
15
16func httpRequest(client *http.Client, hostname string, method string, p string, params interface{}, headers []string) (*http.Response, error) {
17 isGraphQL := p == "graphql"
18 var requestURL string
19 if strings.Contains(p, "://") {
20 requestURL = p
21 } else if isGraphQL {
22 requestURL = ghinstance.GraphQLEndpoint(hostname)
23 } else {
24 // Note that the gh api command takes the path verbatim from the user, so we
25 // intentionally do not route it through safeurl and do not escape it here.
26 requestURL = ghinstance.RESTPrefix(hostname) + strings.TrimPrefix(p, "/")
27 }
28
29 var body io.Reader
30 var bodyIsJSON bool
31
32 switch pp := params.(type) {
33 case map[string]interface{}:
34 if strings.EqualFold(method, "GET") {
35 requestURL = addQuery(requestURL, pp)
36 } else {
37 if isGraphQL {
38 pp = groupGraphQLVariables(pp)
39 }
40 b, err := json.Marshal(pp)
41 if err != nil {
42 return nil, fmt.Errorf("error serializing parameters: %w", err)
43 }
44 body = bytes.NewBuffer(b)
45 bodyIsJSON = true
46 }
47 case io.Reader:
48 body = pp
49 case nil:
50 body = nil
51 default:
52 return nil, fmt.Errorf("unrecognized parameters type: %v", params)
53 }
54
55 req, err := http.NewRequest(strings.ToUpper(method), requestURL, body)
56 if err != nil {
57 return nil, err
58 }
59
60 for _, h := range headers {
61 idx := strings.IndexRune(h, ':')
62 if idx == -1 {
63 return nil, fmt.Errorf("header %q requires a value separated by ':'", h)
64 }
65 name, value := h[0:idx], strings.TrimSpace(h[idx+1:])
66 if strings.EqualFold(name, "Content-Length") {
67 length, err := strconv.ParseInt(value, 10, 0)
68 if err != nil {
69 return nil, err
70 }
71 req.ContentLength = length
72 } else {
73 req.Header.Add(name, value)

Callers 2

apiRunFunction · 0.85
Test_httpRequestFunction · 0.85

Calls 10

GraphQLEndpointFunction · 0.92
RESTPrefixFunction · 0.92
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