Documentation
¶
Overview ¶
Package client provides an HTTP client for the Slack Manager API.
The client wraps github.com/go-resty/resty/v2 with automatic retries, configurable connection pooling, and pluggable logging.
Basic Usage ¶
c := client.New("https://api.example.com",
client.WithAuthToken("my-token"),
client.WithRetryCount(5),
)
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.Send(ctx, alert); err != nil {
log.Fatal(err)
}
Configuration ¶
All configuration is supplied as Option functions passed to New. Invalid values are silently ignored and the default is retained; all configuration is validated when Client.Connect is called.
Retry Behaviour ¶
DefaultRetryPolicy retries on HTTP 429 (rate limit) and 5xx server errors, and on transient connection errors. It respects the Retry-After response header for rate-limit backoff. Context cancellation, deadline exceeded, and DNS resolution errors are never retried. Supply a custom function via WithRetryPolicy to override this behaviour.
Authentication ¶
Token-based authentication is configured with WithAuthToken (and optionally WithAuthScheme). HTTP Basic authentication is configured with WithBasicAuth. The two methods are mutually exclusive.
Logging ¶
Implement RequestLogger and supply it via WithRequestLogger to integrate with your logging library. The default NoopLogger discards all log output. Ensure your implementation redacts credentials and tokens from request and response bodies before persisting logs.
Index ¶
- func DefaultRetryPolicy(r *resty.Response, err error) bool
- type Client
- func (c *Client) Close()
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) RestyClient() *resty.Client
- func (c *Client) Send(ctx context.Context, alerts ...*types.Alert) error
- func (c *Client) SendWithResponse(ctx context.Context, alerts ...*types.Alert) (*ResponseMetadata, error)
- type NoopLogger
- type Option
- func WithAlertsEndpoint(endpoint string) Option
- func WithAuthScheme(scheme string) Option
- func WithAuthToken(token string) Option
- func WithBasicAuth(username, password string) Option
- func WithDisableKeepAlive(disable bool) Option
- func WithIdleConnTimeout(timeout time.Duration) Option
- func WithMaxConnsPerHost(n int) Option
- func WithMaxIdleConns(n int) Option
- func WithMaxRedirects(n int) Option
- func WithPingEndpoint(endpoint string) Option
- func WithRequestHeader(header, value string) Option
- func WithRequestLogger(logger RequestLogger) Option
- func WithRetryCount(count int) Option
- func WithRetryMaxWaitTime(maxWaitTime time.Duration) Option
- func WithRetryPolicy(policy func(*resty.Response, error) bool) Option
- func WithRetryWaitTime(waitTime time.Duration) Option
- func WithTLSConfig(config *tls.Config) Option
- func WithTimeout(timeout time.Duration) Option
- func WithUserAgent(userAgent string) Option
- type Options
- type RequestLogger
- type ResponseMetadata
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultRetryPolicy ¶
DefaultRetryPolicy is the default retry condition used by Client. It retries on HTTP 429 (rate limit) and 5xx server errors, and on transient connection errors. It does not retry on context cancellation, deadline exceeded, DNS resolution failures, or permanent connection failures (connection refused, network/host unreachable, permission denied).
Supply a custom function via WithRetryPolicy to override this behaviour.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client for sending alerts to the Slack Manager API. Use New to create a Client, then call Client.Connect to establish the connection. Call Client.Close when finished to release resources.
func New ¶
New creates a new Client configured with the given base URL and options. Call Client.Connect before sending alerts.
func (*Client) Close ¶
func (c *Client) Close()
Close releases idle connections held by the client. After Close is called the client should not be reused.
func (*Client) Connect ¶
Connect initializes the HTTP client and validates connectivity by pinging the API. It is safe for concurrent use and only initializes once — if Connect fails, subsequent calls return the same error.
func (*Client) Ping ¶
Ping checks connectivity to the API. Client.Connect must be called first. Use this to verify the connection is still healthy after the initial connect.
func (*Client) RestyClient ¶
RestyClient returns the underlying resty.Client for advanced configuration. Returns nil if Client.Connect has not been called. Use with caution: direct modifications may affect client behaviour.
func (*Client) Send ¶
Send posts one or more alerts to the API. Client.Connect must be called first. Returns an error if the alerts slice is empty or any element is nil.
func (*Client) SendWithResponse ¶ added in v0.2.2
func (c *Client) SendWithResponse(ctx context.Context, alerts ...*types.Alert) (*ResponseMetadata, error)
SendWithResponse posts one or more alerts to the API and returns HTTP response metadata. Client.Connect must be called first. Returns an error if the alerts slice is empty or any element is nil. The returned *ResponseMetadata is non-nil whenever an HTTP response was received (even on non-2xx); it is nil only when a network-level error prevents any response from arriving.
type NoopLogger ¶
type NoopLogger struct{}
NoopLogger is a RequestLogger that silently discards all log messages. It is the default logger used when no logger is provided to New.
func (*NoopLogger) Debugf ¶
func (l *NoopLogger) Debugf(_ string, _ ...any)
func (*NoopLogger) Errorf ¶
func (l *NoopLogger) Errorf(_ string, _ ...any)
func (*NoopLogger) Warnf ¶
func (l *NoopLogger) Warnf(_ string, _ ...any)
type Option ¶
type Option func(*Options)
Option is a functional option for configuring a Client.
func WithAlertsEndpoint ¶
WithAlertsEndpoint sets the API endpoint path used when sending alerts. The default is "alerts". Empty and whitespace-only values are silently ignored and the default is retained.
func WithAuthScheme ¶
WithAuthScheme sets the authentication scheme used with WithAuthToken. The default is "Bearer".
func WithAuthToken ¶
WithAuthToken sets the token sent in the Authorization header. Mutually exclusive with WithBasicAuth; supplying both is rejected when Client.Connect is called.
func WithBasicAuth ¶
WithBasicAuth configures HTTP Basic authentication. Mutually exclusive with WithAuthToken; supplying both is rejected when Client.Connect is called.
func WithDisableKeepAlive ¶
WithDisableKeepAlive controls whether HTTP keep-alive is disabled. When true, a new connection is opened for each request. The default is false.
func WithIdleConnTimeout ¶
WithIdleConnTimeout sets how long an idle keep-alive connection remains in the pool before being closed. The default is 90 seconds. Valid range is 1 second–5 minutes. Values outside this range are silently ignored and the default is retained.
func WithMaxConnsPerHost ¶
WithMaxConnsPerHost sets the maximum total (idle and active) connections per host. The default is 10. Valid range is 1–100. Values outside this range are silently ignored and the default is retained.
func WithMaxIdleConns ¶
WithMaxIdleConns sets the maximum number of idle (keep-alive) connections across all hosts. The default is 100. Values less than 1 are silently ignored and the default is retained.
func WithMaxRedirects ¶
WithMaxRedirects sets the maximum number of redirects to follow. Use 0 to disable redirects entirely. The default is 10. The maximum is 20. Negative values or values greater than 20 are silently ignored and the default is retained.
func WithPingEndpoint ¶
WithPingEndpoint sets the API endpoint path used for health checks. The default is "ping". Empty and whitespace-only values are silently ignored and the default is retained.
func WithRequestHeader ¶
WithRequestHeader adds a custom header to all requests. Both the header name and value are trimmed of leading and trailing whitespace. Empty header names and attempts to override the protected Content-Type and Accept headers are silently ignored.
func WithRequestLogger ¶
func WithRequestLogger(logger RequestLogger) Option
WithRequestLogger sets the logger for HTTP request and error logging. The default is NoopLogger, which discards all output. Nil values are silently ignored and the default is retained.
The logger may receive request and response bodies. Ensure your implementation redacts credentials and tokens before persisting logs.
func WithRetryCount ¶
WithRetryCount sets the number of retry attempts for failed requests. The default is 3. The maximum allowed value is 100. Negative values are silently ignored and the default is retained.
func WithRetryMaxWaitTime ¶
WithRetryMaxWaitTime sets the maximum wait time between retries. The default is 3 seconds. Valid range is 100ms–5 minutes. Must be greater than or equal to WithRetryWaitTime; this constraint is validated when Client.Connect is called. Values outside the range are silently ignored.
func WithRetryPolicy ¶
WithRetryPolicy sets a custom function that decides whether a failed request should be retried. The default is DefaultRetryPolicy, which retries on 429, 5xx, and transient connection errors. Nil values are silently ignored and the default is retained.
func WithRetryWaitTime ¶
WithRetryWaitTime sets the initial wait time between retries. The default is 500ms. Valid range is 100ms–1 minute. Values outside this range are silently ignored and the default is retained.
func WithTLSConfig ¶
WithTLSConfig sets a custom TLS configuration for HTTPS connections. Use this for custom CA certificates, mutual TLS (mTLS), or TLS version constraints. The default is nil, which uses Go's default TLS settings. Nil values are silently ignored.
func WithTimeout ¶
WithTimeout sets the per-request timeout. The default is 30 seconds. Valid range is 1 second–5 minutes. Values outside this range are silently ignored and the default is retained.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header sent with every request. The default is "slack-manager-go-client/1.0". Empty values are silently ignored and the default is retained.
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options holds the configuration for a Client. Use Option functions such as WithRetryCount or WithAuthToken to customise the defaults.
type RequestLogger ¶
type RequestLogger interface {
Errorf(format string, v ...any)
Warnf(format string, v ...any)
Debugf(format string, v ...any)
}
RequestLogger is the interface used by Client for logging HTTP requests and errors. Implement this interface to integrate with your logging library and supply the implementation via WithRequestLogger.
type ResponseMetadata ¶ added in v0.2.2
ResponseMetadata contains metadata from the HTTP response returned by Client.SendWithResponse.