libCallApi

package
v0.28.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package libCallApi provides HTTP client utilities for consuming remote REST APIs.

Index

Constants

View Source
const (
	// GrantTypeClientCredentials is the OAuth2 client_credentials grant type string.
	GrantTypeClientCredentials = "client_credentials"
	// GrantTypePassword is the OAuth2 password grant type string.
	GrantTypePassword = "password"
)

Variables

This section is empty.

Functions

func BasicAuth

func BasicAuth(username, password string) string

BasicAuth returns the base64-encoded basic authentication string for the given credentials.

func ConsumeRestJSON added in v0.9.52

func ConsumeRestJSON[Resp any](w webFramework.WebFramework, c *CallData[Resp]) (*Resp, error)

ConsumeRestJSON executes a remote API call and returns the parsed JSON response.

func DefaultBuilderfunc added in v0.13.17

func DefaultBuilderfunc[Resp any](stat int, rawResp []byte, _ map[string]string) (*Resp, error)

DefaultBuilderfunc is the default response builder that unmarshals JSON into the result type.

func ExtractTrackerID added in v0.27.0

func ExtractTrackerID(rawURL string) (cleanEndpoint, trackerID string)

ExtractTrackerID separates a URL from its trackerId query value. It returns the URL without its query string as cleanEndpoint and the first trackerId query value as trackerID. When the URL has no query string, no trackerId parameter is present, or the trackerId value is empty, trackerID is empty and cleanEndpoint is the original URL with its query string removed.

The lookup is case-insensitive (trackerId, TrackerId, TRACKERID all match). The cleanEndpoint preserves the original scheme/path/host exactly; it is not normalized, because transaction-log or metric code may consume it verbatim.

Malformed query encoding does not cause a panic: the clean endpoint is still returned and trackerID is empty.

func GetJSONResp added in v0.9.52

func GetJSONResp[Resp any](api RemoteAPI, resp *http.Response, Builder func(int, []byte, map[string]string) (*Resp, error)) (*Resp, error)

GetJSONResp reads and parses an HTTP response into a typed result using an optional builder.

func IsClientError added in v0.27.0

func IsClientError(err error) bool

IsClientError returns true if err is a RemoteCallError with a 4xx status code.

func IsForbidden added in v0.27.0

func IsForbidden(err error) bool

IsForbidden returns true if err is a RemoteCallError with HTTP status 401 or 403.

func IsServerError added in v0.27.0

func IsServerError(err error) bool

IsServerError returns true if err is a RemoteCallError with a 5xx status code.

func MockErrorResponse added in v0.17.1

func MockErrorResponse(statusCode int, message string) map[string]interface{}

MockErrorResponse creates a mock error response.

func MockSuccessResponse added in v0.17.1

func MockSuccessResponse(data interface{}) map[string]interface{}

MockSuccessResponse creates a generic success response.

func NewInstrumentedHTTPClient added in v0.27.0

func NewInstrumentedHTTPClient(timeout time.Duration, skipTLS bool) *http.Client

NewInstrumentedHTTPClient creates a dedicated *http.Client with OpenTelemetry transport instrumentation. Each call returns an independent client with its own transport; the client is safe for concurrent use.

Parameters:

  • timeout: client-level timeout. Zero means no client-level timeout (the caller is responsible for cancellation via context).
  • skipTLS: when true, TLS certificate verification is disabled. Defaults to false (verification enabled) for production safety.

The returned client wraps its transport with otelhttp.NewTransport so that outbound HTTP spans are automatically created for requests made through it. This complements—but does not duplicate—the manual span creation in ConsumeRestJSON, because otelhttp.NewTransport only creates child spans when a parent span is already active in the context.

func NewTokenHTTPClient added in v0.24.0

func NewTokenHTTPClient() *http.Client

NewTokenHTTPClient creates a new *http.Client with the default timeout for token requests.

func PrepareCall

func PrepareCall[Resp any](w webFramework.WebFramework, c CallData[Resp]) (*http.Request, error)

PrepareCall constructs an *http.Request from CallData, applying auth, headers, and tracing propagation.

func RemoteCall added in v0.9.52

func RemoteCall[Req, Resp any](w webFramework.WebFramework, param *RemoteCallParamData[Req, Resp]) (*Resp, error)

RemoteCall executes a typed remote API call and returns the parsed response.

func StatusPreservingBuilder added in v0.27.0

func StatusPreservingBuilder[Resp any](statusCode int, rawResp []byte, headers map[string]string) (*Resp, error)

StatusPreservingBuilder is a BuilerFunc that preserves the HTTP status code in a RemoteCallError when the response is not in the 2xx range. On 2xx it unmarshals the JSON body directly (unlike DefaultBuilderfunc which only accepts exactly 200). 204 No Content returns a zero Resp without unmarshalling.

RemoteCallError is returned exclusively for non-2xx HTTP responses. Malformed JSON on a 2xx response returns a wrapped parse error instead.

Use this builder with RemoteCallParamData when you need to distinguish HTTP status codes (401/403/500) in the returned error.

func TransmitRequestWithAuth

func TransmitRequestWithAuth(
	path, api, method string,
	requestByte []byte,
	headers map[string]string,
	parseRemoteResp func([]byte, string, int) (int, map[string]string, any, error),
	consumeHandler func([]byte, string, string, string, string, map[string]string) ([]byte, string, int, error),
) (int, map[string]string, any, error)

TransmitRequestWithAuth sends a request through a consume handler and parses the remote response.

func TransmitSoap

func TransmitSoap[Resp any](request any, url string, debug bool, _ time.Duration) (*Resp, error)

TransmitSoap sends a SOAP request to the given URL and parses the XML response.

Types

type AnimeEpisode added in v0.17.1

type AnimeEpisode struct {
	URL   string `json:"url"`
	Title string `json:"title"`
}

AnimeEpisode represents a single anime episode.

type AnimeEpisodesResponse added in v0.17.1

type AnimeEpisodesResponse struct {
	Data       []AnimeEpisode `json:"data"`
	Pagination struct {
		LastVisiblePage int  `json:"last_visible_page"`
		HasNextPage     bool `json:"has_next_page"`
	} `json:"pagination"`
}

AnimeEpisodesResponse represents the response structure from Jikan API.

type Auth added in v0.12.2

type Auth struct {
	GrantType    string `yaml:"grant-type"`
	User         string `yaml:"user"`
	Password     string `yaml:"password"`
	ClientID     string `yaml:"client-id"`
	ClientSecret string `yaml:"client-secret"`
	AuthURI      string `yaml:"auth-uri"`
}

Auth holds OAuth2/basic authentication credentials and configuration.

type AuthSystem added in v0.12.2

type AuthSystem interface {
	Login(w webFramework.WebFramework) (*TokenCache, libError.Error)
	Refresh(w webFramework.WebFramework, refreshToken string) (*TokenCache, libError.Error)
}

AuthSystem defines the interface for login and token refresh operations.

func NewOAuth2AuthFromAuthData added in v0.24.0

func NewOAuth2AuthFromAuthData(auth Auth, httpClient *http.Client) (AuthSystem, error)

NewOAuth2AuthFromAuthData builds an AuthSystem implementation from Auth data and an HTTP client.

type BuilerFunc added in v0.15.0

type BuilerFunc[Resp any] func(status int, rawResp []byte, headers map[string]string) (*Resp, error)

BuilerFunc is the signature for a response builder function.

type CallAPIInterface added in v0.28.1

type CallAPIInterface interface {
	GetAPI(apiName string) RemoteAPI
}

CallAPIInterface defines the contract for retrieving a RemoteAPI by name.

type CallData

type CallData[Resp any] struct {
	API       RemoteAPI
	Path      string
	Method    string
	Headers   map[string]string
	Req       any
	SSLVerify bool
	BodyType  RequestBodyType
	Timeout   time.Duration
	EnableLog bool
	LogLevel  int
	Builder   func(int, []byte, map[string]string) (*Resp, error)
	Context   context.Context // Context for distributed tracing and request cancellation
	// LogValue is optional and used only for tracing attributes (derived from the caller's LogValue()).
	LogValue slog.Value
	// contains filtered or unexported fields
}

CallData holds all parameters needed to perform an instrumented remote API call.

func (CallData[Resp]) SetLogs added in v0.3.3

func (c CallData[Resp]) SetLogs(req *http.Request) *http.Request

SetLogs attaches an httptrace.ClientTrace to the request for verbose connection logging.

type CallParam added in v0.3.4

type CallParam *CallParamData

CallParam is a pointer alias for CallParamData used in Call.

type CallParamData added in v0.9.16

type CallParamData struct {
	HTTPClient  *http.Client
	Parameters  map[string]any
	Headers     map[string]string
	API         RemoteAPI
	Timeout     time.Duration
	Method      string
	Path        string
	Query       string
	QueryStack  *[]string
	ValidateTLS bool
	EnableLog   bool
	JSONBody    any
	Parser      webFramework.RequestParser `json:"-"` // Parser for distributed tracing and request cancellation
}

CallParamData holds the parameters for a generic remote API call.

func (CallParamData) LogValue added in v0.13.4

func (r CallParamData) LogValue() slog.Value

LogValue returns a structured slog.Value summarizing the call parameters.

type CallResp

type CallResp struct {
	Headers map[string]string
	Status  int
}

CallResp contains the HTTP status and response headers from a remote call.

func ConsumeRest

func ConsumeRest[Resp any](w webFramework.WebFramework, c CallData[Resp]) (*Resp, *response.WsRemoteResponse, *CallResp, error)

ConsumeRest executes a remote API call and returns the parsed response, ws response, and call metadata.

func GetResp

func GetResp[Resp any, Error any](api RemoteAPI, resp *http.Response) (*Resp, *Error, *CallResp, error)

GetResp reads and parses an HTTP response into typed result and error values. TODO replace response.Error with errors.Join(err, libError.New

type CallResult added in v0.3.4

type CallResult[RespType any] struct {
	Resp   *RespType
	WsResp *response.WsRemoteResponse
	Status *CallResp
	Error  error
}

CallResult wraps the outcome of a Call including response, ws response, status, and error.

func Call added in v0.3.4

func Call[RespType any](w webFramework.WebFramework, param CallParam) CallResult[RespType]

Call executes a remote API call and returns a CallResult.

func MultiCall added in v0.3.6

MultiCall executes a sequence of calls, stopping early on non-OK status.

type FakeAPIServer added in v0.17.1

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

FakeAPIServer creates a local test server that mimics external APIs.

func NewFakeAPIServer added in v0.17.1

func NewFakeAPIServer() *FakeAPIServer

NewFakeAPIServer creates a new fake API server for testing.

func (*FakeAPIServer) Close added in v0.17.1

func (f *FakeAPIServer) Close()

Close shuts down the fake server.

func (*FakeAPIServer) URL added in v0.17.1

func (f *FakeAPIServer) URL() string

URL returns the base URL of the fake server.

type OAuth2Auth added in v0.24.0

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

OAuth2Auth implements AuthSystem using OAuth2 grant types (client credentials or password).

func (OAuth2Auth) Login added in v0.24.0

Login authenticates using the configured grant type and returns a token cache.

func (OAuth2Auth) Refresh added in v0.24.0

func (a OAuth2Auth) Refresh(w webFramework.WebFramework, refreshToken string) (*TokenCache, libError.Error)

Refresh refreshes the access token using the given refresh token and returns an updated token cache.

type OAuth2Token added in v0.12.2

type OAuth2Token struct {
	Token      string
	Type       string
	Scope      string
	TimeTaken  time.Time
	ValidUntil time.Duration
}

OAuth2Token represents an OAuth2 access or refresh token with validity timing.

type RemoteAPI added in v0.28.1

type RemoteAPI struct {
	Domain         string            `yaml:"domain" json:"domain"`
	Name           string            `yaml:"name" json:"name"`
	AuthData       Auth              `yaml:"auth" json:"-"`
	Options        map[string]string `yaml:"options" json:"-"`
	Auth           AuthSystem        `yaml:"-" json:"-"`
	TokenCacheLock *sync.Mutex       `yaml:"-" json:"-"`
	TokenCache     *TokenCache       `yaml:"-" json:"-"`
}

RemoteAPI represents a remote API configuration including domain, auth, and options.

func (RemoteAPI) AddBasicAuthHeader added in v0.28.1

func (api RemoteAPI) AddBasicAuthHeader(headers map[string]string) map[string]string

AddBasicAuthHeader sets the Basic Authorization header in the given map and returns it.

func (*RemoteAPI) Authenticate added in v0.28.1

func (api *RemoteAPI) Authenticate(w webFramework.WebFramework) libError.Error

Authenticate ensures the API has a valid access token, refreshing or logging in as needed.

func (*RemoteAPI) EnsureAuthorization added in v0.28.1

func (api *RemoteAPI) EnsureAuthorization(w webFramework.WebFramework, headers map[string]string) libError.Error

EnsureAuthorization populates the Authorization header if missing, using OAuth2 or basic auth.

func (RemoteAPI) GetAuthHeader added in v0.28.1

func (api RemoteAPI) GetAuthHeader() (string, error)

GetAuthHeader returns the bearer-style Authorization header from the cached token.

func (RemoteAPI) GetBasicAuthHeader added in v0.28.1

func (api RemoteAPI) GetBasicAuthHeader() string

GetBasicAuthHeader returns the Basic authentication header value for this API.

type RemoteAPIModel added in v0.28.1

type RemoteAPIModel struct {
	RemoteAPIList map[string]RemoteAPI
}

RemoteAPIModel holds a map of named remote API configurations.

func (RemoteAPIModel) ConsumeRestAPI added in v0.28.1

func (m RemoteAPIModel) ConsumeRestAPI(w webFramework.WebFramework, requestJSON []byte, apiName, path, contentType, method string, headers map[string]string) ([]byte, string, int, error)

ConsumeRestAPI calls a remote REST API and returns the response body, status text, status code, and error.

func (RemoteAPIModel) ConsumeRestBasicAuthAPI added in v0.28.1

func (m RemoteAPIModel) ConsumeRestBasicAuthAPI(w webFramework.WebFramework, requestJSON []byte, apiName, path, contentType, method string, headers map[string]string) ([]byte, string, error)

ConsumeRestBasicAuthAPI calls a remote REST API using basic authentication.

func (RemoteAPIModel) GetAPI added in v0.28.1

func (m RemoteAPIModel) GetAPI(apiName string) RemoteAPI

GetAPI returns the RemoteAPI registered under the given name.

type RemoteCallError added in v0.27.0

type RemoteCallError struct {
	Status int    // HTTP status code from the remote response
	Body   []byte // Raw response body for debugging
	Err    error  // Underlying error (e.g. libError.NewWithDescription)
}

RemoteCallError preserves the original HTTP status code and raw response body from a non-2xx remote API call. It implements error and Unwrap so that callers can use errors.As to extract the status code and body for routing decisions.

func (*RemoteCallError) Error added in v0.27.0

func (e *RemoteCallError) Error() string

Error returns a human-readable description of the remote call error.

func (*RemoteCallError) Unwrap added in v0.27.0

func (e *RemoteCallError) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

type RemoteCallParamData added in v0.9.52

type RemoteCallParamData[Req, Resp any] struct {
	HTTPClient  *http.Client
	Parameters  map[string]any             `json:"-"`
	Headers     map[string]string          `json:"-"`
	API         RemoteAPI                  `json:"api"`
	Timeout     time.Duration              `json:"-"`
	Method      string                     `json:"method"`
	Path        string                     `json:"path"`
	Query       string                     `json:"-"`
	QueryStack  *[]string                  `json:"-"`
	ValidateTLS bool                       `json:"-"`
	EnableLog   bool                       `json:"-"`
	JSONBody    Req                        `json:"body"`
	BodyType    RequestBodyType            `json:"-"`
	Builder     BuilerFunc[Resp]           `json:"-"`
	Parser      webFramework.RequestParser `json:"-"` // Parser for distributed tracing and request cancellation
}

RemoteCallParamData holds the parameters for a typed remote API call.

func (RemoteCallParamData[Req, Resp]) LogValue added in v0.13.4

func (r RemoteCallParamData[Req, Resp]) LogValue() slog.Value

LogValue returns a structured slog.Value summarizing the remote call parameters with masked auth.

type RequestBodyType added in v0.11.15

type RequestBodyType int

RequestBodyType identifies the kind of request body to send.

const (
	// JSON indicates a JSON request body.
	JSON RequestBodyType = iota
	// Form indicates a form-urlencoded request body.
	Form
	// Empty indicates no request body.
	Empty
)

type SimpleTestData added in v0.17.1

type SimpleTestData struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Value string `json:"value"`
}

SimpleTestData represents a simplified test response structure.

type SimpleTestResponse added in v0.17.1

type SimpleTestResponse struct {
	Data   []SimpleTestData `json:"data"`
	Status string           `json:"status"`
	Count  int              `json:"count"`
}

SimpleTestResponse represents a simplified API response.

type TokenCache added in v0.12.2

type TokenCache struct {
	AccessToken  *OAuth2Token
	RefreshToken *OAuth2Token
}

TokenCache stores the current access and refresh tokens for a remote API.

func InitTokenCache added in v0.12.4

func InitTokenCache() (*TokenCache, *sync.Mutex)

InitTokenCache initializes a token cache which will be used across all APIs. It should be called once per remote-api.

func (TokenCache) Expired added in v0.12.9

func (t TokenCache) Expired() bool

Expired reports whether the cached access token has expired.

type TypeList added in v0.3.6

type TypeList interface {
	GetType(int) any
}

TypeList is an interface for retrieving a typed element by index.

Jump to

Keyboard shortcuts

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