auth-runtime/cli/http.go

56 lines
1.1 KiB
Go
Raw Permalink Normal View History

package main
import (
"io"
"net/http"
"strings"
"time"
)
var httpClient = &http.Client{
Timeout: 30 * time.Second,
}
// APIResponse mirrors the TS ApiResponse.
type APIResponse struct {
Status int `json:"status"`
Body string `json:"body"`
}
// doHTTP performs an HTTP request and returns status + body.
func doHTTP(method, url, authToken, body string, extraHeaders map[string]string) (APIResponse, error) {
var bodyReader io.Reader
if body != "" {
bodyReader = strings.NewReader(body)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
return APIResponse{}, err
}
req.Header.Set("Content-Type", "application/json")
if authToken != "" {
req.Header.Set("Authorization", "Bearer "+authToken)
}
for k, v := range extraHeaders {
req.Header.Set(k, v)
}
resp, err := httpClient.Do(req)
if err != nil {
return APIResponse{}, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return APIResponse{}, err
}
return APIResponse{
Status: resp.StatusCode,
Body: string(respBody),
}, nil
}