slack

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

Slack Package

The slack package provides a simple and efficient way to send notifications to Slack channels via webhooks. It follows the Beaver Kit conventions for configuration and initialization.

Features

  • 🚀 Zero-config initialization with environment variables
  • 📨 Send info, warning, and alert messages with pre-formatted styles
  • ⚙️ Configurable default options (channel, username, icon)
  • 🔄 Support for multiple instances
  • 🧪 Easy testing with Reset() function
  • ⏱️ Configurable timeout for HTTP requests

Installation

go get github.com/gobeaver/beaver-kit

Configuration

The package uses environment variables with the BEAVER_ prefix:

Environment Variable Description Default
BEAVER_SLACK_WEBHOOK_URL Slack webhook URL (required) -
BEAVER_SLACK_CHANNEL Default channel for messages -
BEAVER_SLACK_USERNAME Default username for messages Beaver
BEAVER_SLACK_ICON_EMOJI Default emoji icon (e.g., :robot:) -
BEAVER_SLACK_ICON_URL Default icon URL (cannot be used with emoji) -
BEAVER_SLACK_TIMEOUT HTTP request timeout 10s

Usage

Zero-Config Usage

Set the required environment variable and use the package immediately:

package main

import (
    "log"
    "github.com/gobeaver/beaver-kit/slack"
)

func main() {
    // Requires BEAVER_SLACK_WEBHOOK_URL to be set
    if err := slack.Init(); err != nil {
        log.Fatal(err)
    }
    
    // Get the global instance
    service := slack.Slack()
    
    // Send messages
    service.SendInfo("Application started successfully")
    service.SendWarning("CPU usage is high")
    service.SendAlert("Database connection lost!")
}
Direct Configuration

Initialize with explicit configuration:

err := slack.Init(slack.Config{
    WebhookURL: "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
    Channel:    "#monitoring",
    Username:   "MonitorBot",
    IconEmoji:  ":robot_face:",
    Timeout:    15 * time.Second,
})
if err != nil {
    log.Fatal(err)
}

service := slack.Slack()
service.SendInfo("System health check passed")
Multiple Instances

Create separate instances for different purposes:

// Production alerts instance
prodService, err := slack.New(slack.Config{
    WebhookURL: os.Getenv("PROD_WEBHOOK_URL"),
    Channel:    "#prod-alerts",
    Username:   "ProdBot",
    IconEmoji:  ":warning:",
    Timeout:    10 * time.Second,
})

// Development notifications instance
devService, err := slack.New(slack.Config{
    WebhookURL: os.Getenv("DEV_WEBHOOK_URL"),
    Channel:    "#dev-notifications",
    Username:   "DevBot",
    IconEmoji:  ":computer:",
    Timeout:    10 * time.Second,
})

// Use different instances
prodService.SendAlert("Production deployment failed")
devService.SendInfo("Development build completed")
Custom Options per Message

Override default options for specific messages:

service := slack.Slack()

// Send to a different channel
opts := &slack.MessageOptions{
    Channel: "#urgent-alerts",
}
service.SendAlertWithOptions("Critical issue detected", opts)

// Custom appearance
specialOpts := &slack.MessageOptions{
    Channel:   "#releases",
    Username:  "ReleaseBot",
    IconEmoji: ":rocket:",
}
service.SendInfoWithOptions("v2.0.0 deployed to production", specialOpts)
Method Chaining

Configure service options using method chaining:

service := slack.Slack()
service.
    SetDefaultChannel("#notifications").
    SetDefaultUsername("AppBot").
    SetDefaultIcon(":bell:")

service.SendInfo("Configuration updated")

API Reference

Configuration Type
type Config struct {
    WebhookURL string        // Slack webhook URL (required)
    Channel    string        // Default channel for messages
    Username   string        // Default username for messages
    IconEmoji  string        // Default emoji icon
    IconURL    string        // Default icon URL
    Timeout    time.Duration // HTTP request timeout
}
Message Options
type MessageOptions struct {
    Channel   string // Target channel (overrides default)
    Username  string // Bot username (overrides default)
    IconEmoji string // Emoji icon (overrides default)
    IconURL   string // Icon URL (overrides default)
}
Initialization Functions
  • Init(configs ...Config) error - Initialize global instance
  • GetConfig() (*Config, error) - Get config from environment
  • New(cfg Config) (*Service, error) - Create new instance
  • Slack() *Service - Get global instance
  • Reset() - Reset global instance (for testing)
Message Functions
  • SendInfo(message string) (string, error) - Send info message with ℹ️ formatting
  • SendInfoWithOptions(message string, opts *MessageOptions) (string, error)
  • SendWarning(message string) (string, error) - Send warning message with ⚠️ formatting
  • SendWarningWithOptions(message string, opts *MessageOptions) (string, error)
  • SendAlert(message string) (string, error) - Send alert message with ‼️ formatting
  • SendAlertWithOptions(message string, opts *MessageOptions) (string, error)
  • Send(message string, opts *MessageOptions) (string, error) - Send raw message
Configuration Methods
  • SetDefaultChannel(channel string) *Service - Set default channel
  • SetDefaultUsername(username string) *Service - Set default username
  • SetDefaultIcon(iconEmoji string) *Service - Set default emoji icon
  • SetDefaultIconURL(iconURL string) *Service - Set default icon URL

Testing

Use the Reset() function to clean up between tests:

func TestMyFunction(t *testing.T) {
    defer slack.Reset() // Clean up after test
    
    // Mock configuration
    err := slack.Init(slack.Config{
        WebhookURL: "https://example.com/webhook",
        Timeout:    5 * time.Second,
    })
    if err != nil {
        t.Fatal(err)
    }
    
    // Test your code that uses slack
}

Error Handling

The package provides clear error messages for common issues:

service, err := slack.New(slack.Config{
    WebhookURL: "", // This will error
})
// Error: invalid config: invalid configuration: webhook URL required

service, err := slack.New(slack.Config{
    WebhookURL: "https://example.com",
    IconEmoji:  ":robot:",
    IconURL:    "https://example.com/icon.png", // This will error
})
// Error: invalid config: invalid configuration: cannot use both icon_emoji and icon_url

Message Formatting

Messages are automatically formatted based on their type:

  • Info: ℹ️ Your message ℹ️
  • Warning: ⚠️ Your message ⚠️
  • Alert: ‼️ Alert ‼️\nYour message

Examples

See the examples directory for complete working examples:

  • ZeroConfigExample - Using environment variables
  • DirectConfigExample - Direct configuration
  • MultipleInstancesExample - Managing multiple Slack webhooks
  • CustomOptionsExample - Overriding options per message

Best Practices

  1. Use environment variables for configuration in production
  2. Set meaningful defaults at the service level to avoid repetition
  3. Use appropriate message types (Info, Warning, Alert) for clarity
  4. Handle errors from send operations, especially in critical paths
  5. Use Reset() in tests to ensure clean state between test cases
  6. Validate webhook URLs before deploying to production

Getting a Slack Webhook URL

  1. Go to your Slack workspace's App Directory
  2. Search for "Incoming WebHooks" and add it
  3. Choose a channel and click "Add Incoming WebHooks Integration"
  4. Copy the Webhook URL
  5. Set it as BEAVER_SLACK_WEBHOOK_URL environment variable

License

This package is part of the Beaver Kit project. See the main project repository for license information.

Documentation

Overview

Package slack provides methods to send notifications to Slack channels via webhooks.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Configuration errors
	ErrInvalidConfig        = errors.New("invalid configuration")
	ErrWebhookNotConfigured = errors.New("webhook URL not configured")
	ErrNotInitialized       = errors.New("service not initialized")

	// API errors
	ErrRateLimited     = errors.New("slack rate limit exceeded")
	ErrInvalidResponse = errors.New("invalid response from Slack")
	ErrMessageTooLarge = errors.New("message exceeds Slack's size limit")
	ErrInvalidChannel  = errors.New("invalid channel format")
	ErrWebhookFailed   = errors.New("webhook request failed")

	// Retry errors
	ErrMaxRetriesExceeded = errors.New("maximum retries exceeded")
	ErrContextCanceled    = errors.New("context canceled")

	// Security errors
	ErrInputTooLarge      = errors.New("input exceeds maximum size")
	ErrInvalidInput       = errors.New("invalid input detected")
	ErrSanitizationFailed = errors.New("input sanitization failed")
)

Standard errors for the slack package

View Source
var (
	// ErrCircuitOpen is returned when the circuit is open
	ErrCircuitOpen = errors.New("circuit breaker is open")
)

Functions

func Health added in v0.1.1

func Health() error

Health checks if the Slack webhook is accessible

func Init

func Init(configs ...Config) error

Init initializes the global instance with optional config

func Reset

func Reset()

Reset clears the global instance (for testing)

Types

type Attachment added in v0.1.1

type Attachment struct {
	Color      string   `json:"color,omitempty"`
	Fallback   string   `json:"fallback,omitempty"`
	Title      string   `json:"title,omitempty"`
	TitleLink  string   `json:"title_link,omitempty"`
	Text       string   `json:"text,omitempty"`
	Pretext    string   `json:"pretext,omitempty"`
	Footer     string   `json:"footer,omitempty"`
	FooterIcon string   `json:"footer_icon,omitempty"`
	Timestamp  int64    `json:"ts,omitempty"`
	Fields     []Field  `json:"fields,omitempty"`
	MrkdwnIn   []string `json:"mrkdwn_in,omitempty"`
	Blocks     []Block  `json:"blocks,omitempty"`
}

Attachment represents a Slack message attachment

type BatchResult added in v0.1.1

type BatchResult struct {
	Index    int
	Response string
	Error    error
}

BatchResult represents the result of a batch send operation

type Block added in v0.1.1

type Block struct {
	Type     string         `json:"type"`
	Text     *TextObject    `json:"text,omitempty"`
	BlockID  string         `json:"block_id,omitempty"`
	Elements []BlockElement `json:"elements,omitempty"`
	Fields   []TextObject   `json:"fields,omitempty"`
}

Block represents a Slack Block Kit block

func NewContextBlock added in v0.1.1

func NewContextBlock(elements []BlockElement) Block

NewContextBlock creates a new context block

func NewDividerBlock added in v0.1.1

func NewDividerBlock() Block

NewDividerBlock creates a new divider block

func NewHeaderBlock added in v0.1.1

func NewHeaderBlock(text string) Block

NewHeaderBlock creates a new header block

func NewSectionBlock added in v0.1.1

func NewSectionBlock(text string, markdown bool) Block

NewSectionBlock creates a new section block

type BlockElement added in v0.1.1

type BlockElement struct {
	Type     string      `json:"type"`
	Text     *TextObject `json:"text,omitempty"`
	Value    string      `json:"value,omitempty"`
	ActionID string      `json:"action_id,omitempty"`
	URL      string      `json:"url,omitempty"`
}

BlockElement represents an element within a block

func NewButtonElement added in v0.1.1

func NewButtonElement(text, actionID, value string) BlockElement

NewButtonElement creates a new button element

func NewLinkButtonElement added in v0.1.1

func NewLinkButtonElement(text, url string) BlockElement

NewLinkButtonElement creates a new link button element

type Builder added in v0.1.0

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

Builder provides a way to create Slack service instances with custom prefixes

func WithPrefix added in v0.1.0

func WithPrefix(prefix string) *Builder

WithPrefix creates a new Builder with the specified prefix

func (*Builder) Init added in v0.1.0

func (b *Builder) Init() error

Init initializes the global Slack service using the builder's prefix

func (*Builder) New added in v0.1.0

func (b *Builder) New() (*Service, error)

New creates a new Slack service using the builder's prefix

type CircuitBreaker added in v0.1.1

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

CircuitBreaker protects against cascading failures

func NewCircuitBreaker added in v0.1.1

func NewCircuitBreaker(maxFailures int, timeout time.Duration, maxRequests int) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) Allow added in v0.1.1

func (cb *CircuitBreaker) Allow() error

Allow checks if a request is allowed through the circuit

func (*CircuitBreaker) Execute added in v0.1.1

func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() error) error

Execute runs a function with circuit breaker protection

func (*CircuitBreaker) RecordFailure added in v0.1.1

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request

func (*CircuitBreaker) RecordSuccess added in v0.1.1

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request

func (*CircuitBreaker) Reset added in v0.1.1

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker to closed state

func (*CircuitBreaker) State added in v0.1.1

func (cb *CircuitBreaker) State() CircuitState

State returns the current state of the circuit breaker

type CircuitBreakerError added in v0.1.1

type CircuitBreakerError struct {
	State   CircuitState
	Message string
}

CircuitBreakerError represents a circuit breaker error

func (*CircuitBreakerError) Error added in v0.1.1

func (e *CircuitBreakerError) Error() string

type CircuitState added in v0.1.1

type CircuitState int

CircuitState represents the state of a circuit breaker

const (
	CircuitClosed CircuitState = iota
	CircuitOpen
	CircuitHalfOpen
)

type Config

type Config struct {
	WebhookURL string        `env:"WEBHOOK_URL"`
	Channel    string        `env:"CHANNEL"`
	Username   string        `env:"USERNAME,default:Beaver"`
	IconEmoji  string        `env:"ICON_EMOJI"`
	IconURL    string        `env:"ICON_URL"`
	Timeout    time.Duration `env:"TIMEOUT,default:10s"`

	// Retry configuration
	MaxRetries    int           `env:"MAX_RETRIES,default:3"`
	RetryDelay    time.Duration `env:"RETRY_DELAY,default:1s"`
	RetryMaxDelay time.Duration `env:"RETRY_MAX_DELAY,default:30s"`
	RetryJitter   bool          `env:"RETRY_JITTER,default:true"`

	// Rate limiting
	RateLimit int `env:"RATE_LIMIT,default:1"`  // requests per second
	RateBurst int `env:"RATE_BURST,default:10"` // burst size

	// Circuit breaker
	CircuitThreshold   int           `env:"CIRCUIT_THRESHOLD,default:5"`    // failures before opening
	CircuitTimeout     time.Duration `env:"CIRCUIT_TIMEOUT,default:60s"`    // time before half-open
	CircuitMaxRequests int           `env:"CIRCUIT_MAX_REQUESTS,default:1"` // requests in half-open state

	// Security
	MaxMessageSize int  `env:"MAX_MESSAGE_SIZE,default:40000"` // Slack's limit is 40KB
	SanitizeInput  bool `env:"SANITIZE_INPUT,default:true"`
	RedactErrors   bool `env:"REDACT_ERRORS,default:true"`

	// Monitoring
	EnableMetrics bool   `env:"ENABLE_METRICS,default:false"`
	EnableLogging bool   `env:"ENABLE_LOGGING,default:false"`
	LogLevel      string `env:"LOG_LEVEL,default:info"`

	// Debug configuration
	Debug bool `env:"DEBUG,default:false"`
}

Config defines slack configuration

func GetConfig

func GetConfig(opts ...config.LoadOptions) (*Config, error)

GetConfig returns config loaded from environment

type Field added in v0.1.1

type Field struct {
	Title string `json:"title"`
	Value string `json:"value"`
	Short bool   `json:"short,omitempty"`
}

Field represents a field in an attachment

type LogLevel added in v0.1.1

type LogLevel int

LogLevel represents logging level

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

type Logger added in v0.1.1

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

Logger provides structured logging for the Slack service

func NewLogger added in v0.1.1

func NewLogger(enabled bool, level string) *Logger

NewLogger creates a new logger

func (*Logger) Debug added in v0.1.1

func (l *Logger) Debug(format string, args ...interface{})

Debug logs debug message

func (*Logger) Error added in v0.1.1

func (l *Logger) Error(format string, args ...interface{})

Error logs error message

func (*Logger) Info added in v0.1.1

func (l *Logger) Info(format string, args ...interface{})

Info logs info message

func (*Logger) Warn added in v0.1.1

func (l *Logger) Warn(format string, args ...interface{})

Warn logs warning message

type Message

type Message struct {
	Text      string `json:"text"`
	Channel   string `json:"channel,omitempty"`
	Username  string `json:"username,omitempty"`
	IconEmoji string `json:"icon_emoji,omitempty"`
	IconURL   string `json:"icon_url,omitempty"`
}

Message represents a Slack message to be sent

type MessageOptions

type MessageOptions struct {
	Channel   string
	Username  string
	IconEmoji string
	IconURL   string
}

MessageOptions contains optional parameters for Slack messages

type Metrics added in v0.1.1

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

Metrics tracks various metrics for the Slack service

func NewMetrics added in v0.1.1

func NewMetrics() *Metrics

NewMetrics creates a new metrics instance

func (*Metrics) GetStats added in v0.1.1

func (m *Metrics) GetStats() Stats

GetStats returns current statistics

func (*Metrics) RecordCircuitOpen added in v0.1.1

func (m *Metrics) RecordCircuitOpen()

RecordCircuitOpen records when circuit breaker opens

func (*Metrics) RecordFailure added in v0.1.1

func (m *Metrics) RecordFailure(err error)

RecordFailure records a failed message

func (*Metrics) RecordMessage added in v0.1.1

func (m *Metrics) RecordMessage()

RecordMessage records a message attempt

func (*Metrics) RecordRateLimit added in v0.1.1

func (m *Metrics) RecordRateLimit()

RecordRateLimit records a rate limit hit

func (*Metrics) RecordSuccess added in v0.1.1

func (m *Metrics) RecordSuccess(latency time.Duration)

RecordSuccess records a successful message

type NoOpLimiter added in v0.1.1

type NoOpLimiter struct{}

NoOpLimiter is a rate limiter that allows all requests

func (*NoOpLimiter) Allow added in v0.1.1

func (l *NoOpLimiter) Allow(ctx context.Context) error

Allow always returns nil

func (*NoOpLimiter) Wait added in v0.1.1

func (l *NoOpLimiter) Wait(ctx context.Context) error

Wait always returns nil immediately

type RateLimitedError added in v0.1.1

type RateLimitedError struct {
	RetryAfter time.Duration
}

RateLimitedError wraps an error with rate limit information

func (*RateLimitedError) Error added in v0.1.1

func (e *RateLimitedError) Error() string

type RateLimiter added in v0.1.1

type RateLimiter interface {
	Allow(ctx context.Context) error
	Wait(ctx context.Context) error
}

RateLimiter provides rate limiting functionality

type RequestLogger added in v0.1.1

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

RequestLogger logs requests with sensitive data redaction

func NewRequestLogger added in v0.1.1

func NewRequestLogger(logger *Logger, redact bool) *RequestLogger

NewRequestLogger creates a new request logger

func (*RequestLogger) LogRequest added in v0.1.1

func (rl *RequestLogger) LogRequest(ctx context.Context, payload string)

LogRequest logs an outgoing request

func (*RequestLogger) LogResponse added in v0.1.1

func (rl *RequestLogger) LogResponse(ctx context.Context, statusCode int, body string)

LogResponse logs an incoming response

type RichMessage added in v0.1.1

type RichMessage struct {
	Text        string       `json:"text,omitempty"`
	Channel     string       `json:"channel,omitempty"`
	Username    string       `json:"username,omitempty"`
	IconEmoji   string       `json:"icon_emoji,omitempty"`
	IconURL     string       `json:"icon_url,omitempty"`
	Blocks      []Block      `json:"blocks,omitempty"`
	Attachments []Attachment `json:"attachments,omitempty"`
}

RichMessage represents a rich Slack message with blocks and attachments

type Service

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

Service represents a Slack notification service

func New

func New(cfg Config) (*Service, error)

New creates a new instance with given config

func Slack

func Slack() *Service

Slack returns the global slack service instance

func (*Service) GetStats added in v0.1.1

func (s *Service) GetStats() *Stats

GetStats returns service statistics

func (*Service) Health added in v0.1.1

func (s *Service) Health(ctx context.Context) error

Health performs a health check without sending a message

func (*Service) Ping added in v0.1.1

func (s *Service) Ping(ctx context.Context) error

Ping sends a test message to verify webhook connectivity

func (*Service) PingWithOptions added in v0.1.1

func (s *Service) PingWithOptions(ctx context.Context, opts *MessageOptions) error

PingWithOptions sends a test message with custom options

func (*Service) Send

func (s *Service) Send(message string, opts *MessageOptions) (string, error)

Send sends a raw message to Slack (deprecated: use SendWithContext)

func (*Service) SendAlert

func (s *Service) SendAlert(message string) (string, error)

SendAlert sends an alert message to Slack

func (*Service) SendAlertWithContext added in v0.1.1

func (s *Service) SendAlertWithContext(ctx context.Context, message string) (string, error)

SendAlertWithContext sends an alert message to Slack with context

func (*Service) SendAlertWithOptions

func (s *Service) SendAlertWithOptions(message string, opts *MessageOptions) (string, error)

SendAlertWithOptions sends an alert message to Slack with custom options

func (*Service) SendAlertWithOptionsContext added in v0.1.1

func (s *Service) SendAlertWithOptionsContext(ctx context.Context, message string, opts *MessageOptions) (string, error)

SendAlertWithOptionsContext sends an alert message with context and options

func (*Service) SendBatch added in v0.1.1

func (s *Service) SendBatch(ctx context.Context, messages []string, opts *MessageOptions) []BatchResult

SendBatch sends multiple messages in parallel

func (*Service) SendError added in v0.1.1

func (s *Service) SendError(err error) (string, error)

SendError sends an error message to Slack with proper redaction

func (*Service) SendErrorWithContext added in v0.1.1

func (s *Service) SendErrorWithContext(ctx context.Context, err error) (string, error)

SendErrorWithContext sends an error message to Slack with context

func (*Service) SendInfo

func (s *Service) SendInfo(message string) (string, error)

SendInfo sends an informational message to Slack

func (*Service) SendInfoWithContext added in v0.1.1

func (s *Service) SendInfoWithContext(ctx context.Context, message string) (string, error)

SendInfoWithContext sends an informational message to Slack with context

func (*Service) SendInfoWithOptions

func (s *Service) SendInfoWithOptions(message string, opts *MessageOptions) (string, error)

SendInfoWithOptions sends an informational message to Slack with custom options

func (*Service) SendInfoWithOptionsContext added in v0.1.1

func (s *Service) SendInfoWithOptionsContext(ctx context.Context, message string, opts *MessageOptions) (string, error)

SendInfoWithOptionsContext sends an informational message with context and options

func (*Service) SendRichBatch added in v0.1.1

func (s *Service) SendRichBatch(ctx context.Context, messages []*RichMessage) []BatchResult

SendRichBatch sends multiple rich messages in parallel

func (*Service) SendRichMessage added in v0.1.1

func (s *Service) SendRichMessage(ctx context.Context, msg *RichMessage) (string, error)

SendRichMessage sends a rich message with blocks and attachments

func (*Service) SendSuccess added in v0.1.1

func (s *Service) SendSuccess(message string) (string, error)

SendSuccess sends a success message to Slack

func (*Service) SendSuccessWithContext added in v0.1.1

func (s *Service) SendSuccessWithContext(ctx context.Context, message string) (string, error)

SendSuccessWithContext sends a success message to Slack with context

func (*Service) SendWarning

func (s *Service) SendWarning(message string) (string, error)

SendWarning sends a warning message to Slack

func (*Service) SendWarningWithContext added in v0.1.1

func (s *Service) SendWarningWithContext(ctx context.Context, message string) (string, error)

SendWarningWithContext sends a warning message to Slack with context

func (*Service) SendWarningWithOptions

func (s *Service) SendWarningWithOptions(message string, opts *MessageOptions) (string, error)

SendWarningWithOptions sends a warning message to Slack with custom options

func (*Service) SendWarningWithOptionsContext added in v0.1.1

func (s *Service) SendWarningWithOptionsContext(ctx context.Context, message string, opts *MessageOptions) (string, error)

SendWarningWithOptionsContext sends a warning message with context and options

func (*Service) SendWithContext added in v0.1.1

func (s *Service) SendWithContext(ctx context.Context, message string, opts *MessageOptions) (string, error)

SendWithContext sends a raw message to Slack with context support

func (*Service) SetDebug added in v0.1.1

func (s *Service) SetDebug(debug bool) *Service

SetDebug enables or disables debug logging

func (*Service) SetDefaultChannel

func (s *Service) SetDefaultChannel(channel string) *Service

SetDefaultChannel sets the default channel for all messages sent by this service

func (*Service) SetDefaultIcon

func (s *Service) SetDefaultIcon(iconEmoji string) *Service

SetDefaultIcon sets the default icon emoji for all messages sent by this service

func (*Service) SetDefaultIconURL

func (s *Service) SetDefaultIconURL(iconURL string) *Service

SetDefaultIconURL sets the default icon URL for all messages sent by this service

func (*Service) SetDefaultUsername

func (s *Service) SetDefaultUsername(username string) *Service

SetDefaultUsername sets the default username for all messages sent by this service

func (*Service) Shutdown added in v0.1.1

func (s *Service) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the service

type SlidingWindowLimiter added in v0.1.1

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

SlidingWindowLimiter implements sliding window rate limiting

func NewSlidingWindowLimiter added in v0.1.1

func NewSlidingWindowLimiter(limit int, window time.Duration) *SlidingWindowLimiter

NewSlidingWindowLimiter creates a new sliding window rate limiter

func (*SlidingWindowLimiter) Allow added in v0.1.1

func (l *SlidingWindowLimiter) Allow(ctx context.Context) error

Allow checks if a request is allowed

func (*SlidingWindowLimiter) Wait added in v0.1.1

Wait waits until a request is allowed

type Stats added in v0.1.1

type Stats struct {
	MessagesSent      int64
	MessagesSucceeded int64
	MessagesFailed    int64
	RateLimitHits     int64
	CircuitOpens      int64
	AverageLatency    time.Duration
	ErrorCounts       map[string]int64
}

Stats represents service statistics

type TextObject added in v0.1.1

type TextObject struct {
	Type  string `json:"type"` // "plain_text" or "mrkdwn"
	Text  string `json:"text"`
	Emoji bool   `json:"emoji,omitempty"`
}

TextObject represents text in Slack blocks

type TokenBucketLimiter added in v0.1.1

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

TokenBucketLimiter implements token bucket rate limiting

func NewTokenBucketLimiter added in v0.1.1

func NewTokenBucketLimiter(rate int, burst int) *TokenBucketLimiter

NewTokenBucketLimiter creates a new token bucket rate limiter

func (*TokenBucketLimiter) Allow added in v0.1.1

func (l *TokenBucketLimiter) Allow(ctx context.Context) error

Allow checks if a request is allowed

func (*TokenBucketLimiter) Wait added in v0.1.1

func (l *TokenBucketLimiter) Wait(ctx context.Context) error

Wait waits until a request is allowed

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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