apiRequest executes an HTTP POST to an internal Bytebase API endpoint. It handles URL building, auth forwarding, Connect-RPC headers, and JSON marshaling.
(ctx context.Context, path string, body any)
| 22 | // apiRequest executes an HTTP POST to an internal Bytebase API endpoint. |
| 23 | // It handles URL building, auth forwarding, Connect-RPC headers, and JSON marshaling. |
| 24 | func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiResponse, error) { |
| 25 | var bodyBytes []byte |
| 26 | var err error |
| 27 | if body != nil { |
| 28 | bodyBytes, err = json.Marshal(body) |
| 29 | if err != nil { |
| 30 | return nil, errors.Wrap(err, "failed to marshal request body") |
| 31 | } |
| 32 | } else { |
| 33 | bodyBytes = []byte("{}") |
| 34 | } |
| 35 | |
| 36 | url := fmt.Sprintf("http://localhost:%d%s", s.profile.Port, path) |
| 37 | httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes)) |
| 38 | if err != nil { |
| 39 | return nil, errors.Wrap(err, "failed to create HTTP request") |
| 40 | } |
| 41 | |
| 42 | httpReq.Header.Set("Content-Type", "application/json") |
| 43 | httpReq.Header.Set("Connect-Protocol-Version", "1") |
| 44 | |
| 45 | if token := getAccessToken(ctx); token != "" { |
| 46 | httpReq.Header.Set("Authorization", "Bearer "+token) |
| 47 | } |
| 48 | |
| 49 | client := &http.Client{Timeout: 30 * time.Second} |
| 50 | resp, err := client.Do(httpReq) |
| 51 | if err != nil { |
| 52 | return nil, errors.Wrap(err, "failed to execute API request") |
| 53 | } |
| 54 | defer resp.Body.Close() |
| 55 | |
| 56 | respBody, err := io.ReadAll(resp.Body) |
| 57 | if err != nil { |
| 58 | return nil, errors.Wrap(err, "failed to read response body") |
| 59 | } |
| 60 | |
| 61 | return &apiResponse{ |
| 62 | Status: resp.StatusCode, |
| 63 | Body: json.RawMessage(respBody), |
| 64 | Headers: resp.Header, |
| 65 | }, nil |
| 66 | } |
| 67 | |
| 68 | // parseError extracts the error message from an API error response body. |
| 69 | func parseError(body json.RawMessage) string { |