MCPcopy Create free account
hub / github.com/daodst/chat / PostJSON

Function PostJSON

internal/httputil/http.go:32–85  ·  view source on GitHub ↗

PostJSON performs a POST request with JSON on an internal HTTP API

(
	ctx context.Context, span opentracing.Span, httpClient *http.Client,
	apiURL string, request, response interface{},
)

Source from the content-addressed store, hash-verified

30
31// PostJSON performs a POST request with JSON on an internal HTTP API
32func PostJSON(
33 ctx context.Context, span opentracing.Span, httpClient *http.Client,
34 apiURL string, request, response interface{},
35) error {
36 jsonBytes, err := json.Marshal(request)
37 if err != nil {
38 return err
39 }
40
41 parsedAPIURL, err := url.Parse(apiURL)
42 if err != nil {
43 return err
44 }
45
46 parsedAPIURL.Path = InternalPathPrefix + strings.TrimLeft(parsedAPIURL.Path, "/")
47 apiURL = parsedAPIURL.String()
48
49 req, err := http.NewRequest(http.MethodPost, apiURL, bytes.NewReader(jsonBytes))
50 if err != nil {
51 return err
52 }
53
54 // Mark the span as being an RPC client.
55 ext.SpanKindRPCClient.Set(span)
56 carrier := opentracing.HTTPHeadersCarrier(req.Header)
57 tracer := opentracing.GlobalTracer()
58
59 if err = tracer.Inject(span.Context(), opentracing.HTTPHeaders, carrier); err != nil {
60 return err
61 }
62
63 req.Header.Set("Content-Type", "application/json")
64
65 res, err := httpClient.Do(req.WithContext(ctx))
66 if res != nil {
67 defer (func() { err = res.Body.Close() })()
68 }
69 if err != nil {
70 return err
71 }
72 if res.StatusCode != http.StatusOK {
73 var errorBody struct {
74 Message string `json:"message"`
75 }
76 if _, ok := response.(*api.PerformKeyBackupResponse); ok { // TODO: remove this, once cross-boundary errors are a thing
77 return nil
78 }
79 if msgerr := json.NewDecoder(res.Body).Decode(&errorBody); msgerr == nil {
80 return fmt.Errorf("internal API: %d from %s: %s", res.StatusCode, apiURL, errorBody.Message)
81 }
82 return fmt.Errorf("internal API: %d from %s", res.StatusCode, apiURL)
83 }
84 return json.NewDecoder(res.Body).Decode(response)
85}

Callers

nothing calls this directly

Calls 5

ContextMethod · 0.80
SetMethod · 0.65
DoMethod · 0.65
CloseMethod · 0.65
StringMethod · 0.45

Tested by

no test coverage detected