client

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 15 Imported by: 0

README

slackmgr/go-client

Go Reference Go Report Card CI

A Go HTTP client for the Slack Manager API. Wraps resty with built-in retry logic, connection pooling, and pluggable logging.

Installation

go get github.com/slackmgr/go-client

Requires Go 1.25+.

Usage

import (
    "context"
    "log"

    client "github.com/slackmgr/go-client"
    "github.com/slackmgr/types"
)

ctx := context.Background()

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

alert := &types.Alert{
    // populate alert fields
}

if err := c.Send(ctx, alert); err != nil {
    log.Fatal(err)
}

Connect validates configuration, initializes the connection pool, and pings the API. It is safe for concurrent use and will only initialize once — if it fails, subsequent calls return the same error. Call Close when finished to release idle connections.

Configuration

All options are provided via With* constructor functions.

Option Default Description
WithRetryCount(int) 3 Number of retry attempts (max 100)
WithRetryWaitTime(time.Duration) 500ms Initial wait time between retries (100ms–1min)
WithRetryMaxWaitTime(time.Duration) 3s Maximum wait time between retries (100ms–5min)
WithRetryPolicy(func(*resty.Response, error) bool) DefaultRetryPolicy Custom retry condition function
WithRequestLogger(RequestLogger) NoopLogger Logger for HTTP requests and errors
WithRequestHeader(header, value string) Add a custom header to all requests
WithAuthToken(string) Token for Authorization header (mutually exclusive with WithBasicAuth)
WithAuthScheme(string) "Bearer" Authentication scheme used with WithAuthToken
WithBasicAuth(username, password string) HTTP Basic authentication (mutually exclusive with WithAuthToken)
WithTimeout(time.Duration) 30s Per-request timeout (1s–5min)
WithUserAgent(string) "slack-manager-go-client/1.0" User-Agent header value
WithMaxIdleConns(int) 100 Maximum idle connections across all hosts
WithMaxConnsPerHost(int) 10 Maximum connections per host (max 100)
WithIdleConnTimeout(time.Duration) 90s How long idle connections remain in the pool (1s–5min)
WithDisableKeepAlive(bool) false Disable HTTP keep-alive (new connection per request)
WithMaxRedirects(int) 10 Maximum redirects to follow (0 disables redirects, max 20)
WithTLSConfig(*tls.Config) nil Custom TLS configuration for mTLS, custom CAs, etc.
WithAlertsEndpoint(string) "alerts" API endpoint path for sending alerts
WithPingEndpoint(string) "ping" API endpoint path for health checks
Retry behaviour

DefaultRetryPolicy retries on HTTP 429 (rate limit), 5xx server errors, and transient connection errors. It does not retry on context cancellation, deadline exceeded, or DNS resolution failures. Retry-After response headers are respected for rate-limit backoff.

Supply a custom function via WithRetryPolicy to override this behaviour.

Logging

Implement the RequestLogger interface to integrate with your logging library:

type RequestLogger interface {
    Errorf(format string, v ...any)
    Warnf(format string, v ...any)
    Debugf(format string, v ...any)
}

Note: The logger may receive request and response bodies. Ensure your implementation redacts credentials and tokens before persisting logs.

License

This project is licensed under the MIT License — see the LICENSE file for details.

Copyright (c) 2026 Peter Aglen

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultRetryPolicy

func DefaultRetryPolicy(r *resty.Response, err error) bool

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

func New(baseURL string, opts ...Option) *Client

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

func (c *Client) Connect(ctx context.Context) error

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

func (c *Client) Ping(ctx context.Context) error

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

func (c *Client) RestyClient() *resty.Client

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

func (c *Client) Send(ctx context.Context, alerts ...*types.Alert) error

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.

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

func WithAlertsEndpoint(endpoint string) Option

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

func WithAuthScheme(scheme string) Option

WithAuthScheme sets the authentication scheme used with WithAuthToken. The default is "Bearer".

func WithAuthToken

func WithAuthToken(token string) Option

WithAuthToken sets the token sent in the Authorization header. Mutually exclusive with WithBasicAuth; supplying both is rejected when Client.Connect is called.

func WithBasicAuth

func WithBasicAuth(username, password string) Option

WithBasicAuth configures HTTP Basic authentication. Mutually exclusive with WithAuthToken; supplying both is rejected when Client.Connect is called.

func WithDisableKeepAlive

func WithDisableKeepAlive(disable bool) Option

WithDisableKeepAlive controls whether HTTP keep-alive is disabled. When true, a new connection is opened for each request. The default is false.

func WithIdleConnTimeout

func WithIdleConnTimeout(timeout time.Duration) Option

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

func WithMaxConnsPerHost(n int) Option

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

func WithMaxIdleConns(n int) Option

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

func WithMaxRedirects(n int) Option

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

func WithPingEndpoint(endpoint string) Option

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

func WithRequestHeader(header, value string) Option

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

func WithRetryCount(count int) Option

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

func WithRetryMaxWaitTime(maxWaitTime time.Duration) Option

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

func WithRetryPolicy(policy func(*resty.Response, error) bool) Option

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

func WithRetryWaitTime(waitTime time.Duration) Option

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

func WithTLSConfig(config *tls.Config) Option

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

func WithTimeout(timeout time.Duration) Option

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

func WithUserAgent(userAgent string) Option

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.

func (*Options) Validate

func (o *Options) Validate() error

Validate checks all options fields for validity and returns an error if any are invalid.

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.

Jump to

Keyboard shortcuts

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