English | 繁體中文
samhook is a lightweight Go library designed to provide a simple and easy-to-use API for sending Slack and Mattermost webhook messages.
- Minimal external dependencies: Uses only high-performance JSON library
- Minimal abstraction: Direct mapping to Slack/Mattermost webhook API
- Simple and easy to use: Provides intuitive API interface
- Strong typing: All data structures have explicit type definitions
- JSON tags: Uses standard JSON tags for serialization
- Optional fields: Uses
omitemptytags to serialize only fields with values
- Multiple input methods: Supports both struct and Reader input methods
- Method chaining: Supports method chaining for better developer experience
- Extensible: Easy to add new features
samhook/
├── message.go # Data structure definitions
├── samhook.go # Core functionality implementation
├── error.go # Error type definitions
├── client.go # HTTP client configuration
└── retry.go # Retry mechanism
Defines three core data structures:
-
Message - Message body
- Contains basic message attributes (text, username, icon, etc.)
- Contains attachment list
-
Attachment - Attachment structure
- Supports rich formatting options
- Supports fields, images, author information, etc.
-
Field - Field structure
- Used to display structured data in attachments
- Supports short fields for side-by-side display
Implements core functionality:
-
Send function
- Receives Message structure
- Serializes to JSON
- Sends HTTP POST request
- Checks HTTP status code and returns detailed errors
-
SendReader function
- Receives io.Reader
- Directly sends HTTP POST request
- Suitable for scenarios with existing JSON data
- Checks HTTP status code and returns detailed errors
-
AddAttachment method
- Adds a single attachment to Message
- Returns *Message to support method chaining
-
AddAttachments method
- Adds multiple attachments to Message
- Returns *Message to support method chaining
Implements error handling functionality:
-
WebhookError type
- Custom error type providing detailed error information
- Supports error classification (network errors, serialization errors, API errors)
- Provides error codes and detailed messages
-
Error constructor functions
NewNetworkError()- Creates network errorNewSerializationError()- Creates serialization errorNewAPIError()- Creates API error
Implements HTTP client configuration functionality:
-
SendWithOptions function
- Supports custom HTTP client configuration
- Uses options pattern
- Supports timeout configuration
-
SendWithContext function
- Supports Context timeout and cancellation
- Uses
http.NewRequestWithContext()
-
ClientOption type
WithTimeout()- Sets timeoutWithClient()- Uses custom client
Implements retry mechanism:
-
SendWithRetry function
- Supports automatic retry for failed requests
- Configurable retry count and interval
- Intelligently determines which errors can be retried
-
ExponentialBackoff type
- Implements exponential backoff strategy
- Supports random jitter
- Configurable initial interval and maximum interval
User Code
↓
Create Message structure
↓
(Optional) Add attachments
↓
Call Send() function
↓
JSON serialization
↓
HTTP POST request
↓
Webhook URL
User Code
↓
Prepare JSON data (io.Reader)
↓
Call SendReader() function
↓
HTTP POST request (directly uses Reader)
↓
Webhook URL
bytes- For creating request bodycontext- Context support (for timeout and cancellation)fmt- String formattingio- Reader interfacemath- Mathematical operations (for exponential backoff)math/rand- Random number generation (for jitter)net- Network error classificationnet/http- HTTP clientnet/url- URL error handlingstrings- String operationstime- Time and timeout control
github.com/bytedance/sonic- High-performance JSON serialization/deserialization library
The project uses a high-performance JSON library, ensuring:
- Fast compilation
- High execution performance
- Optimized memory usage
- Simple dependency management
- ✅ Configurable HTTP client: Supports custom timeout, custom client (
SendWithOptions) - ✅ Response handling: Checks HTTP status code and returns detailed errors
- ✅ Retry mechanism: Supports automatic retry with exponential backoff strategy
- ✅ Context support: Supports timeout and cancellation control
- ✅ Detailed error handling: Custom error type providing error classification and detailed information
- Batch sending: Support sending multiple messages at once
- Async sending: Provide helper functions to simplify async sending
- Rate limiting handling: Automatically handle 429 errors and request queuing
samhook is fully compatible with Slack Incoming Webhooks API, supporting:
- Basic message format
- Attachment format
- Field format
- All standard fields
Mattermost's webhook API is highly compatible with Slack, so samhook can also be used directly with Mattermost.
- ✅ All functions return
error(may be*WebhookError) - ✅ Error classification: network errors, serialization errors, API errors
- ✅ Detailed error information: includes status code, response body, error code, etc.
- ✅ Error classification methods:
IsNetworkError(),IsAPIError(),IsSerializationError() - ✅ Detailed error messages:
DetailedMessage()provides multi-line format
- Network errors (
ErrorTypeNetwork): HTTP request failures, connection errors, etc. - Serialization errors (
ErrorTypeSerialization): JSON serialization failures - API errors (
ErrorTypeAPI): HTTP status codes other than 200 - Unknown errors (
ErrorTypeUnknown): Errors that cannot be classified
Send Request
↓
Error occurred?
↓ Yes
Create WebhookError
↓
Classify error type
↓
Return WebhookError
↓
Users can:
- Check error type
- Get status code
- Get detailed message
- Implement intelligent handling
- Uses
http.DefaultClient(shared connection pool) - Synchronous sending (blocks until completion)
- High-performance serialization (uses sonic JSON library)
- Low latency: Direct HTTP requests, no additional overhead
- Low memory: Minimizes memory allocation
- High throughput: Can be used concurrently (each goroutine is independent)
- Does not validate webhook URL
- Does not encrypt transmission (relies on HTTPS)
- Does not validate response
- URL validation: Validate webhook URL format
- HTTPS enforcement: Enforce HTTPS in production environments
- Response validation: Check HTTP status code
-
✅ Unit tests:
- Data structure serialization tests (
message_test.go) - Error type tests (
samhook_test.go) - Client configuration tests (
client_test.go) - Retry mechanism tests (
retry_test.go)
- Data structure serialization tests (
-
✅ Integration tests:
- Uses
httptestpackage to create mock HTTP servers - Tests various HTTP status code scenarios
- Tests error handling logic
- Uses
-
End-to-end tests:
- Optional integration tests (requires actual webhook URL)
- Marked as integration tests using build tags
Current test coverage is approximately 62%, covering:
- Serialization of all data structures
- Core sending functionality
- Error handling logic
- Client configuration
- Retry mechanism
- Clear module separation: Data structures separated from functionality
- Consistent naming: Follows Go naming conventions
- Complete comments: All public APIs have comments
- Simple code structure: Easy to understand and modify
- Minimized complexity: Avoids over-engineering
- Standardized format: Uses Go standard format