service

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package service provides an HTTP client with features for logging, metrics, and resilience.It supports various functionalities like health checks, circuit-breaker and various authentication.

Package service is a generated GoMock package.

Package service is a generated GoMock package.

Index

Constants

View Source
const (
	ClosedState = iota
	OpenState
)

circuitBreaker states.

View Source
const (
	AlivePath  = "/.well-known/alive"
	HealthPath = "/.well-known/health"
)
View Source
const AuthHeader = "Authorization"

Variables

View Source
var (
	// ErrCircuitOpen indicates that the circuit breaker is open.
	ErrCircuitOpen                        = errors.New("unable to connect to server at host")
	ErrUnexpectedCircuitBreakerResultType = errors.New("unexpected result type from circuit breaker")
)

Functions

func NewCircuitBreaker

func NewCircuitBreaker(config CircuitBreakerConfig, h HTTP) *circuitBreaker

NewCircuitBreaker creates a new circuitBreaker instance based on the provided config.

Types

type APIKeyConfig

type APIKeyConfig struct {
	APIKey string
}

func (*APIKeyConfig) AddOption

func (a *APIKeyConfig) AddOption(h HTTP) HTTP

type AuthErr

type AuthErr struct {
	Err     error
	Message string
}

func (AuthErr) Error

func (o AuthErr) Error() string

type BasicAuthConfig

type BasicAuthConfig struct {
	UserName string
	Password string
}

func (*BasicAuthConfig) AddOption

func (c *BasicAuthConfig) AddOption(h HTTP) HTTP

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Threshold int           // Threshold represents the max no of retry before switching the circuit breaker state.
	Interval  time.Duration // Interval represents the time interval duration between hitting the HealthURL
}

CircuitBreakerConfig holds the configuration for the circuitBreaker.

func (*CircuitBreakerConfig) AddOption

func (cb *CircuitBreakerConfig) AddOption(h HTTP) HTTP

type ConnectionPoolConfig

type ConnectionPoolConfig struct {
	// MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts.
	// If not explicitly set (0), a default of 100 will be used.
	// Negative values will cause validation error.
	MaxIdleConns int

	// MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host.
	// This is the critical setting for microservices making frequent requests to the same host.
	// If set to 0, Go's DefaultMaxIdleConnsPerHost (2) will be used.
	// Negative values will cause validation error.
	// Default Go value: 2 (which is often insufficient for microservices)
	// Recommended: 10-20 for typical microservices, higher for high-traffic services
	MaxIdleConnsPerHost int

	// IdleConnTimeout is the maximum amount of time an idle (keep-alive) connection will remain
	// idle before closing itself.
	// If not explicitly set (0), a default of 90 seconds will be used.
	// Negative values will cause validation error.
	IdleConnTimeout time.Duration
}

ConnectionPoolConfig holds the configuration for HTTP connection pool settings. It customizes the HTTP transport layer to optimize connection reuse for high-frequency requests.

Note: This configuration must be applied first when using multiple options with AddHTTPService, as it needs to access the underlying HTTP client transport. If applied after wrapper options (CircuitBreaker, Retry, OAuth), it will be silently ignored.

Example:

app.AddHTTPService("api-service", "https://api.example.com",
    &service.ConnectionPoolConfig{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 20,
        IdleConnTimeout:     90 * time.Second,
    },
    &service.CircuitBreakerConfig{...}, // Other options after ConnectionPoolConfig
)

func (*ConnectionPoolConfig) AddOption

func (c *ConnectionPoolConfig) AddOption(h HTTP) HTTP

AddOption implements the Options interface to apply connection pool configuration to HTTP service. It modifies the underlying HTTP client's transport to use optimized connection pool settings.

func (*ConnectionPoolConfig) Validate

func (c *ConnectionPoolConfig) Validate() error

Validate checks if the connection pool configuration values are valid.

type DefaultHeaders

type DefaultHeaders struct {
	Headers map[string]string
}

func (*DefaultHeaders) AddOption

func (a *DefaultHeaders) AddOption(h HTTP) HTTP

type ErrorLog

type ErrorLog struct {
	*Log
	ErrorMessage string `json:"errorMessage"`
}

func (*ErrorLog) PrettyPrint

func (el *ErrorLog) PrettyPrint(writer io.Writer)

type HTTP

type HTTP interface {

	// HealthCheck to get the service health and report it to the current application
	HealthCheck(ctx context.Context) *Health
	// contains filtered or unexported methods
}

func NewHTTPService

func NewHTTPService(serviceAddress string, logger Logger, metrics Metrics, options ...Options) HTTP

NewHTTPService function creates a new instance of the httpService struct, which implements the HTTP interface. It initializes the http.Client, url, Tracer, and Logger fields of the httpService struct with the provided values.

func NewRateLimiter

func NewRateLimiter(config RateLimiterConfig, h HTTP) HTTP

NewRateLimiter creates a new unified rate limiter.

type Health

type Health struct {
	Status  string         `json:"status"`
	Details map[string]any `json:"details"`
}

type HealthConfig

type HealthConfig struct {
	HealthEndpoint string
	Timeout        int
}

func (*HealthConfig) AddOption

func (h *HealthConfig) AddOption(svc HTTP) HTTP

type LocalRateLimiterStore

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

LocalRateLimiterStore implements RateLimiterStore using in-memory buckets.

func NewLocalRateLimiterStore

func NewLocalRateLimiterStore() *LocalRateLimiterStore

func (*LocalRateLimiterStore) Allow

func (*LocalRateLimiterStore) StartCleanup

func (l *LocalRateLimiterStore) StartCleanup(ctx context.Context)

func (*LocalRateLimiterStore) StopCleanup

func (l *LocalRateLimiterStore) StopCleanup()

type Log

type Log struct {
	Timestamp     time.Time `json:"timestamp"`
	ResponseTime  int64     `json:"latency"`
	CorrelationID string    `json:"correlationId"`
	ResponseCode  int       `json:"responseCode"`
	HTTPMethod    string    `json:"httpMethod"`
	URI           string    `json:"uri"`
}

func (*Log) PrettyPrint

func (l *Log) PrettyPrint(writer io.Writer)

type Logger

type Logger interface {
	Log(args ...any)
}

type Metrics

type Metrics interface {
	NewCounter(name, desc string)
	NewGauge(name, desc string)
	IncrementCounter(ctx context.Context, name string, labels ...string)
	RecordHistogram(ctx context.Context, name string, value float64, labels ...string)
	SetGauge(name string, value float64, labels ...string)
}

type MockHTTP

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

MockHTTP is a mock of HTTP interface.

func NewMockHTTP

func NewMockHTTP(ctrl *gomock.Controller) *MockHTTP

NewMockHTTP creates a new mock instance.

func (*MockHTTP) Delete

func (m *MockHTTP) Delete(ctx context.Context, api string, body []byte) (*http.Response, error)

Delete mocks base method.

func (*MockHTTP) DeleteWithHeaders

func (m *MockHTTP) DeleteWithHeaders(ctx context.Context, api string, body []byte, headers map[string]string) (*http.Response, error)

DeleteWithHeaders mocks base method.

func (*MockHTTP) EXPECT

func (m *MockHTTP) EXPECT() *MockHTTPMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockHTTP) Get

func (m *MockHTTP) Get(ctx context.Context, api string, queryParams map[string]any) (*http.Response, error)

Get mocks base method.

func (*MockHTTP) GetWithHeaders

func (m *MockHTTP) GetWithHeaders(ctx context.Context, path string, queryParams map[string]any, headers map[string]string) (*http.Response, error)

GetWithHeaders mocks base method.

func (*MockHTTP) HealthCheck

func (m *MockHTTP) HealthCheck(ctx context.Context) *Health

HealthCheck mocks base method.

func (*MockHTTP) Patch

func (m *MockHTTP) Patch(ctx context.Context, api string, queryParams map[string]any, body []byte) (*http.Response, error)

Patch mocks base method.

func (*MockHTTP) PatchWithHeaders

func (m *MockHTTP) PatchWithHeaders(ctx context.Context, api string, queryParams map[string]any, body []byte, headers map[string]string) (*http.Response, error)

PatchWithHeaders mocks base method.

func (*MockHTTP) Post

func (m *MockHTTP) Post(ctx context.Context, path string, queryParams map[string]any, body []byte) (*http.Response, error)

Post mocks base method.

func (*MockHTTP) PostWithHeaders

func (m *MockHTTP) PostWithHeaders(ctx context.Context, path string, queryParams map[string]any, body []byte, headers map[string]string) (*http.Response, error)

PostWithHeaders mocks base method.

func (*MockHTTP) Put

func (m *MockHTTP) Put(ctx context.Context, api string, queryParams map[string]any, body []byte) (*http.Response, error)

Put mocks base method.

func (*MockHTTP) PutWithHeaders

func (m *MockHTTP) PutWithHeaders(ctx context.Context, api string, queryParams map[string]any, body []byte, headers map[string]string) (*http.Response, error)

PutWithHeaders mocks base method.

type MockHTTPMockRecorder

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

MockHTTPMockRecorder is the mock recorder for MockHTTP.

func (*MockHTTPMockRecorder) Delete

func (mr *MockHTTPMockRecorder) Delete(ctx, api, body any) *gomock.Call

Delete indicates an expected call of Delete.

func (*MockHTTPMockRecorder) DeleteWithHeaders

func (mr *MockHTTPMockRecorder) DeleteWithHeaders(ctx, api, body, headers any) *gomock.Call

DeleteWithHeaders indicates an expected call of DeleteWithHeaders.

func (*MockHTTPMockRecorder) Get

func (mr *MockHTTPMockRecorder) Get(ctx, api, queryParams any) *gomock.Call

Get indicates an expected call of Get.

func (*MockHTTPMockRecorder) GetWithHeaders

func (mr *MockHTTPMockRecorder) GetWithHeaders(ctx, path, queryParams, headers any) *gomock.Call

GetWithHeaders indicates an expected call of GetWithHeaders.

func (*MockHTTPMockRecorder) HealthCheck

func (mr *MockHTTPMockRecorder) HealthCheck(ctx any) *gomock.Call

HealthCheck indicates an expected call of HealthCheck.

func (*MockHTTPMockRecorder) Patch

func (mr *MockHTTPMockRecorder) Patch(ctx, api, queryParams, body any) *gomock.Call

Patch indicates an expected call of Patch.

func (*MockHTTPMockRecorder) PatchWithHeaders

func (mr *MockHTTPMockRecorder) PatchWithHeaders(ctx, api, queryParams, body, headers any) *gomock.Call

PatchWithHeaders indicates an expected call of PatchWithHeaders.

func (*MockHTTPMockRecorder) Post

func (mr *MockHTTPMockRecorder) Post(ctx, path, queryParams, body any) *gomock.Call

Post indicates an expected call of Post.

func (*MockHTTPMockRecorder) PostWithHeaders

func (mr *MockHTTPMockRecorder) PostWithHeaders(ctx, path, queryParams, body, headers any) *gomock.Call

PostWithHeaders indicates an expected call of PostWithHeaders.

func (*MockHTTPMockRecorder) Put

func (mr *MockHTTPMockRecorder) Put(ctx, api, queryParams, body any) *gomock.Call

Put indicates an expected call of Put.

func (*MockHTTPMockRecorder) PutWithHeaders

func (mr *MockHTTPMockRecorder) PutWithHeaders(ctx, api, queryParams, body, headers any) *gomock.Call

PutWithHeaders indicates an expected call of PutWithHeaders.

type MockMetrics

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

MockMetrics is a mock of Metrics interface.

func NewMockMetrics

func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics

NewMockMetrics creates a new mock instance.

func (*MockMetrics) EXPECT

func (m *MockMetrics) EXPECT() *MockMetricsMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockMetrics) IncrementCounter

func (m *MockMetrics) IncrementCounter(ctx context.Context, name string, labels ...string)

IncrementCounter mocks base method.

func (*MockMetrics) NewCounter

func (m *MockMetrics) NewCounter(name, desc string)

NewCounter mocks base method.

func (*MockMetrics) NewGauge

func (m *MockMetrics) NewGauge(name, desc string)

NewGauge mocks base method.

func (*MockMetrics) RecordHistogram

func (m *MockMetrics) RecordHistogram(ctx context.Context, name string, value float64, labels ...string)

RecordHistogram mocks base method.

func (*MockMetrics) SetGauge

func (m *MockMetrics) SetGauge(name string, value float64, labels ...string)

SetGauge mocks base method.

type MockMetricsMockRecorder

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

MockMetricsMockRecorder is the mock recorder for MockMetrics.

func (*MockMetricsMockRecorder) IncrementCounter

func (mr *MockMetricsMockRecorder) IncrementCounter(ctx, name any, labels ...any) *gomock.Call

IncrementCounter indicates an expected call of IncrementCounter.

func (*MockMetricsMockRecorder) NewCounter

func (mr *MockMetricsMockRecorder) NewCounter(name, desc any) *gomock.Call

NewCounter indicates an expected call of NewCounter.

func (*MockMetricsMockRecorder) NewGauge

func (mr *MockMetricsMockRecorder) NewGauge(name, desc any) *gomock.Call

NewGauge indicates an expected call of NewGauge.

func (*MockMetricsMockRecorder) RecordHistogram

func (mr *MockMetricsMockRecorder) RecordHistogram(ctx, name, value any, labels ...any) *gomock.Call

RecordHistogram indicates an expected call of RecordHistogram.

func (*MockMetricsMockRecorder) SetGauge

func (mr *MockMetricsMockRecorder) SetGauge(name, value any, labels ...any) *gomock.Call

SetGauge indicates an expected call of SetGauge.

type MockhttpClient

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

MockhttpClient is a mock of httpClient interface.

func NewMockhttpClient

func NewMockhttpClient(ctrl *gomock.Controller) *MockhttpClient

NewMockhttpClient creates a new mock instance.

func (*MockhttpClient) Delete

func (m *MockhttpClient) Delete(ctx context.Context, api string, body []byte) (*http.Response, error)

Delete mocks base method.

func (*MockhttpClient) DeleteWithHeaders

func (m *MockhttpClient) DeleteWithHeaders(ctx context.Context, api string, body []byte, headers map[string]string) (*http.Response, error)

DeleteWithHeaders mocks base method.

func (*MockhttpClient) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockhttpClient) Get

func (m *MockhttpClient) Get(ctx context.Context, api string, queryParams map[string]any) (*http.Response, error)

Get mocks base method.

func (*MockhttpClient) GetWithHeaders

func (m *MockhttpClient) GetWithHeaders(ctx context.Context, path string, queryParams map[string]any, headers map[string]string) (*http.Response, error)

GetWithHeaders mocks base method.

func (*MockhttpClient) Patch

func (m *MockhttpClient) Patch(ctx context.Context, api string, queryParams map[string]any, body []byte) (*http.Response, error)

Patch mocks base method.

func (*MockhttpClient) PatchWithHeaders

func (m *MockhttpClient) PatchWithHeaders(ctx context.Context, api string, queryParams map[string]any, body []byte, headers map[string]string) (*http.Response, error)

PatchWithHeaders mocks base method.

func (*MockhttpClient) Post

func (m *MockhttpClient) Post(ctx context.Context, path string, queryParams map[string]any, body []byte) (*http.Response, error)

Post mocks base method.

func (*MockhttpClient) PostWithHeaders

func (m *MockhttpClient) PostWithHeaders(ctx context.Context, path string, queryParams map[string]any, body []byte, headers map[string]string) (*http.Response, error)

PostWithHeaders mocks base method.

func (*MockhttpClient) Put

func (m *MockhttpClient) Put(ctx context.Context, api string, queryParams map[string]any, body []byte) (*http.Response, error)

Put mocks base method.

func (*MockhttpClient) PutWithHeaders

func (m *MockhttpClient) PutWithHeaders(ctx context.Context, api string, queryParams map[string]any, body []byte, headers map[string]string) (*http.Response, error)

PutWithHeaders mocks base method.

type MockhttpClientMockRecorder

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

MockhttpClientMockRecorder is the mock recorder for MockhttpClient.

func (*MockhttpClientMockRecorder) Delete

func (mr *MockhttpClientMockRecorder) Delete(ctx, api, body any) *gomock.Call

Delete indicates an expected call of Delete.

func (*MockhttpClientMockRecorder) DeleteWithHeaders

func (mr *MockhttpClientMockRecorder) DeleteWithHeaders(ctx, api, body, headers any) *gomock.Call

DeleteWithHeaders indicates an expected call of DeleteWithHeaders.

func (*MockhttpClientMockRecorder) Get

func (mr *MockhttpClientMockRecorder) Get(ctx, api, queryParams any) *gomock.Call

Get indicates an expected call of Get.

func (*MockhttpClientMockRecorder) GetWithHeaders

func (mr *MockhttpClientMockRecorder) GetWithHeaders(ctx, path, queryParams, headers any) *gomock.Call

GetWithHeaders indicates an expected call of GetWithHeaders.

func (*MockhttpClientMockRecorder) Patch

func (mr *MockhttpClientMockRecorder) Patch(ctx, api, queryParams, body any) *gomock.Call

Patch indicates an expected call of Patch.

func (*MockhttpClientMockRecorder) PatchWithHeaders

func (mr *MockhttpClientMockRecorder) PatchWithHeaders(ctx, api, queryParams, body, headers any) *gomock.Call

PatchWithHeaders indicates an expected call of PatchWithHeaders.

func (*MockhttpClientMockRecorder) Post

func (mr *MockhttpClientMockRecorder) Post(ctx, path, queryParams, body any) *gomock.Call

Post indicates an expected call of Post.

func (*MockhttpClientMockRecorder) PostWithHeaders

func (mr *MockhttpClientMockRecorder) PostWithHeaders(ctx, path, queryParams, body, headers any) *gomock.Call

PostWithHeaders indicates an expected call of PostWithHeaders.

func (*MockhttpClientMockRecorder) Put

func (mr *MockhttpClientMockRecorder) Put(ctx, api, queryParams, body any) *gomock.Call

Put indicates an expected call of Put.

func (*MockhttpClientMockRecorder) PutWithHeaders

func (mr *MockhttpClientMockRecorder) PutWithHeaders(ctx, api, queryParams, body, headers any) *gomock.Call

PutWithHeaders indicates an expected call of PutWithHeaders.

type OAuthConfig

type OAuthConfig struct {
	// ClientID is the application's ID.
	ClientID string

	// ClientSecret is the application's secret.
	ClientSecret string

	// TokenURL is the resource server's token endpoint
	// URL. This is a constant specific to each server.
	TokenURL string

	// Scope specifies optional requested permissions.
	Scopes []string

	// EndpointParams specifies additional parameters for requests to the token endpoint.
	EndpointParams url.Values

	// AuthStyle represents how requests for tokens are authenticated to the server
	// Defaults to [oauth2.AuthStyleAutoDetect]
	AuthStyle oauth2.AuthStyle
}

OAuthConfig describes a 2-legged OAuth2 flow, with both the client application information and the server's endpoint URLs.

func (*OAuthConfig) AddOption

func (c *OAuthConfig) AddOption(svc HTTP) HTTP

type Options

type Options interface {
	AddOption(h HTTP) HTTP
}

func NewAPIKeyConfig

func NewAPIKeyConfig(apiKey string) (Options, error)

func NewBasicAuthConfig

func NewBasicAuthConfig(username, password string) (Options, error)

func NewOAuthConfig

func NewOAuthConfig(clientID, secret, tokenURL string, scopes []string, params url.Values, authStyle oauth2.AuthStyle) (Options, error)

func WithAttributes

func WithAttributes(attributes map[string]string) Options

WithAttributes returns an Option that sets the attributes of the HTTP service.

type RateLimitError

type RateLimitError struct {
	ServiceKey string
	RetryAfter time.Duration
}

RateLimitError represents a rate limiting error.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) StatusCode

func (*RateLimitError) StatusCode() int

StatusCode Implement StatusCodeResponder so Responder picks correct HTTP code.

type RateLimiterConfig

type RateLimiterConfig struct {
	Requests float64                    // Number of requests allowed
	Window   time.Duration              // Time window (e.g., time.Minute, time.Hour)
	Burst    int                        // Maximum burst capacity (must be > 0)
	KeyFunc  func(*http.Request) string // Optional custom key extraction
	Store    RateLimiterStore
}

RateLimiterConfig with custom keying support.

func (*RateLimiterConfig) AddOption

func (config *RateLimiterConfig) AddOption(h HTTP) HTTP

AddOption allows RateLimiterConfig to be used as a service.Options.

func (*RateLimiterConfig) RequestsPerSecond

func (config *RateLimiterConfig) RequestsPerSecond() float64

RequestsPerSecond converts the configured rate to requests per second.

func (*RateLimiterConfig) Validate

func (config *RateLimiterConfig) Validate() error

Validate checks if the configuration is valid. Validate checks if the configuration is valid and sets defaults.

type RateLimiterStore

type RateLimiterStore interface {
	Allow(ctx context.Context, key string, config RateLimiterConfig) (allowed bool, retryAfter time.Duration, err error)
	StartCleanup(ctx context.Context)
	StopCleanup()
}

RateLimiterStore abstracts the storage and cleanup for rate limiter buckets.

type RedisRateLimiterStore

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

RedisRateLimiterStore implements RateLimiterStore using Redis.

func NewRedisRateLimiterStore

func NewRedisRateLimiterStore(client *kiteRedis.Redis) *RedisRateLimiterStore

func (*RedisRateLimiterStore) Allow

func (*RedisRateLimiterStore) StartCleanup

func (*RedisRateLimiterStore) StartCleanup(_ context.Context)

func (*RedisRateLimiterStore) StopCleanup

func (*RedisRateLimiterStore) StopCleanup()

type Response

type Response struct {
	Body       []byte
	StatusCode int
	// contains filtered or unexported fields
}

func (*Response) GetHeader

func (r *Response) GetHeader(key string) string

type RetryConfig

type RetryConfig struct {
	MaxRetries int
}

func (*RetryConfig) AddOption

func (r *RetryConfig) AddOption(h HTTP) HTTP

Jump to

Keyboard shortcuts

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