MCPcopy Create free account
hub / github.com/LMCache/LMCache / HTTPPostJSON

Function HTTPPostJSON

operator/test/utils/http.go:105–134  ·  view source on GitHub ↗

HTTPPostJSON issues a POST with a JSON-encoded body and decodes the 2xx response body into out (when non-nil). Returns the parsed JSON status code so callers that care about distinguishing 200 vs 201 can check it themselves.

(ctx context.Context, url string, body, out any)

Source from the content-addressed store, hash-verified

103// status code so callers that care about distinguishing 200 vs 201 can
104// check it themselves.
105func HTTPPostJSON(ctx context.Context, url string, body, out any) error {
106 buf, err := json.Marshal(body)
107 if err != nil {
108 return fmt.Errorf("encode POST %s body: %w", url, err)
109 }
110 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(buf))
111 if err != nil {
112 return fmt.Errorf("build POST %s: %w", url, err)
113 }
114 req.Header.Set("Content-Type", "application/json")
115 resp, err := httpJSONClient.Do(req)
116 if err != nil {
117 return fmt.Errorf("POST %s: %w", url, err)
118 }
119 defer func() { _ = resp.Body.Close() }()
120 respBody, err := io.ReadAll(resp.Body)
121 if err != nil {
122 return fmt.Errorf("read POST %s body: %w", url, err)
123 }
124 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
125 return fmt.Errorf("POST %s: status %d body=%s", url, resp.StatusCode, string(respBody))
126 }
127 if out == nil {
128 return nil
129 }
130 if err := json.Unmarshal(respBody, out); err != nil {
131 return fmt.Errorf("decode JSON from POST %s: %w\nbody=%s", url, err, string(respBody))
132 }
133 return nil
134}
135
136// WaitHTTP200 polls url with GET until it returns 2xx or the timeout
137// elapses. Tighter than HTTPGetJSON because it tolerates transient

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected