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

Function PostJSON

clientapi/routing/voip.go:238–279  ·  view source on GitHub ↗

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

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

Source from the content-addressed store, hash-verified

236
237// PostJSON performs a POST request with JSON on an internal HTTP API
238func PostJSON(
239 ctx context.Context, httpClient *http.Client,
240 apiURL string, request, response interface{},
241) error {
242 jsonBytes, err := json.Marshal(request)
243 if err != nil {
244 return err
245 }
246
247 parsedAPIURL, err := url.Parse(apiURL)
248 if err != nil {
249 return err
250 }
251
252 parsedAPIURL.Path = strings.TrimLeft(parsedAPIURL.Path, "/")
253 apiURL = parsedAPIURL.String()
254
255 req, err := http.NewRequest(http.MethodPost, apiURL, bytes.NewReader(jsonBytes))
256 if err != nil {
257 return err
258 }
259
260 req.Header.Set("Content-Type", "application/json")
261
262 res, err := httpClient.Do(req.WithContext(ctx))
263 if res != nil {
264 defer (func() { err = res.Body.Close() })()
265 }
266 if err != nil {
267 return err
268 }
269 if res.StatusCode != http.StatusOK {
270 var errorBody struct {
271 Message string `json:"message"`
272 }
273 if msgerr := json.NewDecoder(res.Body).Decode(&errorBody); msgerr == nil {
274 return fmt.Errorf("internal API: %d from %s: %s", res.StatusCode, apiURL, errorBody.Message)
275 }
276 return fmt.Errorf("internal API: %d from %s", res.StatusCode, apiURL)
277 }
278 return json.NewDecoder(res.Body).Decode(response)
279}

Callers 3

RequestTurnServerFunction · 0.70
AddTmpAuthInfoFunction · 0.70
DelTmpAuthInfoFunction · 0.70

Calls 4

SetMethod · 0.65
DoMethod · 0.65
CloseMethod · 0.65
StringMethod · 0.45

Tested by

no test coverage detected