http

package
v3.61.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 14 Imported by: 0

README

HTTP Client Package

This package provides a common HTTP client with standardized headers and error handling for Buildkite API requests.

Features

  • Standardized authorization header handling
  • Common error handling for API responses
  • Support for different HTTP methods (GET, POST, PUT, DELETE)
  • JSON request and response handling
  • Configurable base URL and user agent

Usage

Creating a client
import (
    "github.com/buildkite/cli/v3/internal/http"
)

// Basic client with token
client := http.NewClient("your-api-token")

// Client with custom base URL
client := http.NewClient(
    "your-api-token",
    http.WithBaseURL("https://api.example.com"),
)

// Client with custom user agent
client := http.NewClient(
    "your-api-token",
    http.WithUserAgent("my-app/1.0"),
)

// Client with custom HTTP client
client := http.NewClient(
    "your-api-token",
    http.WithHTTPClient(customHTTPClient),
)
Making requests
// GET request
var response SomeResponseType
err := client.Get(ctx, "/endpoint", &response)

// POST request with body
requestBody := map[string]string{"key": "value"}
var response SomeResponseType
err := client.Post(ctx, "/endpoint", requestBody, &response)

// PUT request
err := client.Put(ctx, "/endpoint", requestBody, &response)

// DELETE request
err := client.Delete(ctx, "/endpoint", &response)

// Custom method
err := client.Do(ctx, "PATCH", "/endpoint", requestBody, &response)
Error handling
err := client.Get(ctx, "/endpoint", &response)
if err != nil {
    // Check if it's an HTTP error
    if httpErr, ok := err.(*http.ErrorResponse); ok {
        fmt.Printf("HTTP error: %d %s\n", httpErr.StatusCode, httpErr.Status)
        fmt.Printf("Response body: %s\n", httpErr.Body)
    } else {
        fmt.Printf("Other error: %v\n", err)
    }
}

Documentation

Index

Constants

View Source
const (
	// DefaultMaxRateLimitRetries is the default number of times to retry a
	// rate-limited request.
	DefaultMaxRateLimitRetries = 3
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthTransport added in v3.42.0

type AuthTransport struct {
	Base        http.RoundTripper
	TokenSource *TokenSource
	UserAgent   string
}

AuthTransport injects the Authorization header from a TokenSource on every outgoing request. It should wrap the base transport so that RefreshTransport (which sits outside it) can override the header on retries.

func (*AuthTransport) RoundTrip added in v3.42.0

func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an HTTP client that handles common operations for Buildkite API requests

func NewClient

func NewClient(token string, opts ...ClientOption) *Client

NewClient creates a new HTTP client with the given token and options

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, endpoint string, v interface{}) error

Delete performs a DELETE request to the specified endpoint

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, endpoint string, body interface{}, v interface{}) error

Do performs an HTTP request with the given method, endpoint, and body.

func (*Client) Get

func (c *Client) Get(ctx context.Context, endpoint string, v interface{}) error

Get performs a GET request to the specified endpoint

func (*Client) Post

func (c *Client) Post(ctx context.Context, endpoint string, body interface{}, v interface{}) error

Post performs a POST request to the specified endpoint with the given body

func (*Client) Put

func (c *Client) Put(ctx context.Context, endpoint string, body interface{}, v interface{}) error

Put performs a PUT request to the specified endpoint with the given body

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that modifies a Client

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets the base URL for API requests

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets the underlying HTTP client

func WithHeaders added in v3.60.1

func WithHeaders(headers http.Header) ClientOption

WithHeaders sets extra headers for requests, overriding the defaults

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent sets the User-Agent header for requests

type ErrorResponse

type ErrorResponse struct {
	StatusCode int
	Status     string
	URL        string
	Body       []byte
	Headers    http.Header
}

ErrorResponse represents an error response from the API

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

Error implements the error interface

func (*ErrorResponse) IsBadRequest added in v3.8.0

func (e *ErrorResponse) IsBadRequest() bool

IsBadRequest returns true if the error is a 400 Bad Request

func (*ErrorResponse) IsForbidden added in v3.8.0

func (e *ErrorResponse) IsForbidden() bool

IsForbidden returns true if the error is a 403 Forbidden

func (*ErrorResponse) IsNotFound added in v3.8.0

func (e *ErrorResponse) IsNotFound() bool

IsNotFound returns true if the error is a 404 Not Found

func (*ErrorResponse) IsServerError added in v3.8.0

func (e *ErrorResponse) IsServerError() bool

IsServerError returns true if the error is a 5xx Server Error

func (*ErrorResponse) IsTooManyRequests added in v3.19.0

func (e *ErrorResponse) IsTooManyRequests() bool

IsTooManyRequests returns true if the error is a 429 Too Many Requests

func (*ErrorResponse) IsUnauthorized added in v3.8.0

func (e *ErrorResponse) IsUnauthorized() bool

IsUnauthorized returns true if the error is a 401 Unauthorized

type OnRateLimitFunc added in v3.35.0

type OnRateLimitFunc func(attempt int, delay time.Duration)

OnRateLimitFunc is called before sleeping for a rate-limit backoff. attempt is zero-indexed; delay is how long the transport will sleep.

type RateLimitTransport added in v3.35.0

type RateLimitTransport struct {
	// Transport is the underlying RoundTripper. If nil, http.DefaultTransport
	// is used.
	Transport http.RoundTripper

	// MaxRetries is the maximum number of retry attempts on 429. Zero means
	// no retries; negative values are treated as zero.
	MaxRetries int

	// MaxRetryDelay caps the sleep duration for any single retry. Zero means
	// no cap is applied.
	MaxRetryDelay time.Duration

	// OnRateLimit is an optional callback invoked before each backoff sleep.
	OnRateLimit OnRateLimitFunc
}

RateLimitTransport wraps an http.RoundTripper and automatically retries requests that receive an HTTP 429 response, sleeping for the duration indicated by the RateLimit-Reset header.

func NewRateLimitTransport added in v3.35.0

func NewRateLimitTransport(transport http.RoundTripper) *RateLimitTransport

NewRateLimitTransport returns a RateLimitTransport wrapping the given transport with sensible defaults.

func (*RateLimitTransport) RoundTrip added in v3.35.0

func (t *RateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper. On a 429 response it reads the RateLimit-Reset header (seconds until the rate-limit window resets) and sleeps for that duration before retrying, up to MaxRetries times.

type RefreshTransport added in v3.42.0

type RefreshTransport struct {
	Base        http.RoundTripper
	Org         string
	Keyring     credentialStore
	TokenSource *TokenSource
	// contains filtered or unexported fields
}

RefreshTransport wraps an http.RoundTripper to automatically refresh expired OAuth access tokens using a stored refresh token.

On a 401 response it:

  1. Acquires a mutex to serialise concurrent refreshes.
  2. Checks whether the token has already been refreshed by another goroutine (compare-after-lock).
  3. If not, exchanges the refresh token for new tokens.
  4. Persists the new tokens and updates the shared TokenSource.
  5. Retries the original request with the new token.

func (*RefreshTransport) RoundTrip added in v3.42.0

func (t *RefreshTransport) RoundTrip(req *http.Request) (*http.Response, error)

type TokenSource added in v3.42.0

type TokenSource struct {
	// contains filtered or unexported fields
}

TokenSource provides thread-safe access to the current access token. It is shared between auth-injection points (REST, GraphQL) and RefreshTransport so that a refreshed token is immediately visible to all subsequent requests.

func NewTokenSource added in v3.42.0

func NewTokenSource(token string) *TokenSource

NewTokenSource creates a TokenSource initialised with the given token.

func (*TokenSource) SetToken added in v3.42.0

func (ts *TokenSource) SetToken(token string)

SetToken updates the current access token.

func (*TokenSource) Token added in v3.42.0

func (ts *TokenSource) Token() string

Token returns the current access token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL