libCallApi

package
v0.28.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	GrantTypeClientCredentials = "client_credentials"
	GrantTypePassword          = "password"
)

Variables

This section is empty.

Functions

func BasicAuth

func BasicAuth(username, password string) string

func ConsumeRestJSON added in v0.9.52

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

func DefaultBuilderfunc added in v0.13.17

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

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)

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

func PrepareCall

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

func RemoteCall added in v0.9.52

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

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)

func TransmitSoap

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

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"`
}

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)
}

func NewOAuth2AuthFromAuthData added in v0.24.0

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

type BuilerFunc added in v0.15.0

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

type CallApiInterface

type CallApiInterface interface {
	GetApi(apiName string) RemoteApi
}

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
}

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

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

type CallParam added in v0.3.4

type CallParam *CallParamData

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
}

func (CallParamData) LogValue added in v0.13.4

func (r CallParamData) LogValue() slog.Value

type CallResp

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

func ConsumeRest

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

func GetResp

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

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
}

func Call added in v0.3.4

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

func MultiCall added in v0.3.6

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
}

func (OAuth2Auth) Login added in v0.24.0

func (OAuth2Auth) Refresh added in v0.24.0

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

type OAuth2Token added in v0.12.2

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

type RemoteApi

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:"-"`
}

func (RemoteApi) AddBasicAuthHeader added in v0.12.2

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

func (*RemoteApi) Authenticate added in v0.12.2

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

func (*RemoteApi) EnsureAuthorization added in v0.24.0

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

func (RemoteApi) GetAuthHeader added in v0.12.4

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

func (RemoteApi) GetBasicAuthHeader added in v0.12.2

func (api RemoteApi) GetBasicAuthHeader() string

type RemoteApiModel

type RemoteApiModel struct {
	RemoteApiList map[string]RemoteApi
}

func (RemoteApiModel) ConsumeRestApi

func (m RemoteApiModel) ConsumeRestApi(w webFramework.WebFramework, requestJson []byte, apiName, path, contentType, method string, headers map[string]string) ([]byte, string, int, error)

func (RemoteApiModel) ConsumeRestBasicAuthApi

func (m RemoteApiModel) ConsumeRestBasicAuthApi(w webFramework.WebFramework, requestJson []byte, apiName, path, contentType, method string, headers map[string]string) ([]byte, string, error)

func (RemoteApiModel) GetApi

func (m RemoteApiModel) GetApi(apiName string) RemoteApi

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

func (*RemoteCallError) Unwrap added in v0.27.0

func (e *RemoteCallError) Unwrap() error

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
}

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

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

type RequestBodyType added in v0.11.15

type RequestBodyType int
const (
	JSON RequestBodyType = iota
	Form
	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
}

func InitTokenCache added in v0.12.4

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

initilaizes a token cache which will be used across all APIs should be called once per remote-api

func (TokenCache) Expired added in v0.12.9

func (t TokenCache) Expired() bool

type TypeList added in v0.3.6

type TypeList interface {
	GetType(int) any
}

Jump to

Keyboard shortcuts

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