samhook

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2025 License: MIT Imports: 13 Imported by: 0

README

samhook

English | 繁體中文

A lightweight Go library for sending Slack and Mattermost webhook messages.

Features

  • Lightweight: Minimal external dependencies, uses high-performance JSON library
  • Type-safe: Complete Go type definitions
  • Method chaining: Supports method chaining for better developer experience
  • Flexible input: Supports both struct and Reader input methods
  • Error handling: Detailed error types and classifications
  • Configurable: Supports custom HTTP client and timeout settings
  • Retry mechanism: Optional retry functionality with exponential backoff

Installation

go get github.com/circleyu/samhook

Quick Start

Basic Usage
package main

import (
    "log"
    "github.com/circleyu/samhook"
)

func main() {
    webhookURL := "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
    
    msg := samhook.Message{
        Text:     "Hello from samhook!",
        Username: "samhook-bot",
    }
    
    err := samhook.Send(webhookURL, msg)
    if err != nil {
        log.Fatal(err)
    }
}
Using Attachments
msg := samhook.Message{
    Text: "System Notification",
}

attachment := samhook.Attachment{
    Color: samhook.Good,
    Title: "Operation Successful",
    Text:  "All tasks completed",
}

msg.AddAttachment(attachment)
samhook.Send(webhookURL, msg)
Error Handling
err := samhook.Send(webhookURL, msg)
if err != nil {
    if webhookErr, ok := err.(*samhook.WebhookError); ok {
        if webhookErr.IsNetworkError() {
            // Handle network error, can retry
        } else if webhookErr.IsAPIError() {
            statusCode := webhookErr.GetStatusCode()
            if statusCode == 429 {
                // Handle rate limiting
            }
        }
    }
}
Using Custom Client
import (
    "time"
    "github.com/circleyu/samhook"
)

// Use custom timeout
err := samhook.SendWithOptions(webhookURL, msg,
    samhook.WithTimeout(30 * time.Second),
)

// Use Context
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := samhook.SendWithContext(ctx, webhookURL, msg)
Using Retry Mechanism
opts := samhook.DefaultRetryOptions
opts.MaxRetries = 5

err := samhook.SendWithRetry(webhookURL, msg, opts)

Documentation

Project Structure

samhook/
├── go.mod          # Go module definition
├── message.go      # Message data structure definitions
├── samhook.go      # Core sending functionality
├── error.go        # Error type definitions
├── client.go       # HTTP client configuration
├── retry.go        # Retry mechanism
├── message_test.go # Data structure tests
├── samhook_test.go # Core functionality tests
└── README.md       # Project documentation

License

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

Documentation

Index

Constants

View Source
const (
	ErrorTypeNetwork       = "network"
	ErrorTypeSerialization = "serialization"
	ErrorTypeAPI           = "api"
	ErrorTypeUnknown       = "unknown"
)

錯誤類型常數

View Source
const (
	ErrorCodeNetworkTimeout    = "NETWORK_TIMEOUT"
	ErrorCodeNetworkConnection = "NETWORK_CONNECTION"
	ErrorCodeNetworkDNS        = "NETWORK_DNS"
	ErrorCodeSerializationJSON = "SERIALIZATION_JSON"
	ErrorCodeAPIUnauthorized   = "API_UNAUTHORIZED"
	ErrorCodeAPIForbidden      = "API_FORBIDDEN"
	ErrorCodeAPINotFound       = "API_NOT_FOUND"
	ErrorCodeAPIRateLimit      = "API_RATE_LIMIT"
	ErrorCodeAPIServerError    = "API_SERVER_ERROR"
)

錯誤代碼常數

View Source
const Danger string = "#FF0000"

Danger is a predefined color for a dangerous condition (red)

View Source
const DefaultTimeout = 10 * time.Second

DefaultTimeout 預設超時時間

View Source
const Good string = "#00FF00"

Good is a predefined color for a normal information (green)

View Source
const Warning string = "#FFBB00"

Warning is a predefined color for a warning (yellow)

Variables

View Source
var DefaultRetryOptions = RetryOptions{
	MaxRetries: 3,
	Interval:   1 * time.Second,
	Backoff: &ExponentialBackoff{
		InitialInterval: 1 * time.Second,
		MaxInterval:     30 * time.Second,
		Multiplier:      2.0,
		Jitter:          true,
	},
}

DefaultRetryOptions 預設重試選項

Functions

func Send

func Send(url string, msg Message) error

Send 發送message

func SendReader

func SendReader(url string, r io.Reader) error

SendReader 發送message

func SendWithContext

func SendWithContext(ctx context.Context, url string, msg Message, opts ...ClientOption) error

SendWithContext 使用 Context 發送訊息

func SendWithOptions

func SendWithOptions(url string, msg Message, opts ...ClientOption) error

SendWithOptions 使用選項發送訊息

func SendWithRetry

func SendWithRetry(url string, msg Message, opts RetryOptions, clientOpts ...ClientOption) error

SendWithRetry 帶重試的發送,支援自訂客戶端配置

func SetLogger

func SetLogger(logger Logger)

SetLogger 設置包級別的日誌記錄器

func SetLoggerWriter

func SetLoggerWriter(w io.Writer)

SetLoggerWriter 使用 io.Writer 設置包級別的日誌記錄器

func ValidateWebhookURL

func ValidateWebhookURL(webhookURL string) error

ValidateWebhookURL 驗證 webhook URL 格式和協議

Types

type Attachment

type Attachment struct {
	Fallback   string  `json:"fallback,omitempty"`
	Color      string  `json:"color,omitempty"`
	Pretext    string  `json:"pretext,omitempty"`
	AuthorName string  `json:"author_name,omitempty"`
	AuthorLink string  `json:"author_link,omitempty"`
	AuthorIcon string  `json:"author_icon,omitempty"`
	Title      string  `json:"title,omitempty"`
	TitleLink  string  `json:"title_link,omitempty"`
	Text       string  `json:"text,omitempty"`
	ImageURL   string  `json:"image_url,omitempty"`
	Fields     []Field `json:"fields,omitempty"`
	Footer     string  `json:"footer,omitempty"`
	FooterIcon string  `json:"footer_icon,omitempty"`
	ThumbURL   string  `json:"thumb_url,omitempty"`
}

Attachment attachment主體

type ClientOption

type ClientOption func(*http.Client)

ClientOption 客戶端選項

func WithClient

func WithClient(client *http.Client) ClientOption

WithClient 使用自訂 HTTP 客戶端

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 設置超時

type ExponentialBackoff

type ExponentialBackoff struct {
	InitialInterval time.Duration
	MaxInterval     time.Duration
	Multiplier      float64
	Jitter          bool
}

ExponentialBackoff 指數退避

func (*ExponentialBackoff) NextInterval

func (eb *ExponentialBackoff) NextInterval(attempt int) time.Duration

NextInterval 計算下一次重試間隔

type Field

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

Field field主體

type Logger

type Logger interface {
	LogRequest(url string, method string, duration time.Duration, err error)
}

Logger 定義日誌記錄介面

type Message

type Message struct {
	Parse       string       `json:"parse,omitempty"`
	Username    string       `json:"username,omitempty"`
	IconURL     string       `json:"icon_url,omitempty"`
	IconEmoji   string       `json:"icon_emoji,omitempty"`
	Channel     string       `json:"channel,omitempty"`
	Text        string       `json:"text,omitempty"`
	Attachments []Attachment `json:"attachments,omitempty"`
}

Message message主體

func (*Message) AddAttachment

func (m *Message) AddAttachment(attachment Attachment) *Message

AddAttachment 添加一個attachment

func (*Message) AddAttachments

func (m *Message) AddAttachments(attachments []Attachment) *Message

AddAttachments 添加多個attachment

type RetryOptions

type RetryOptions struct {
	MaxRetries int
	Interval   time.Duration
	Backoff    *ExponentialBackoff
}

RetryOptions 重試選項

type WebhookError

type WebhookError struct {
	// Type 錯誤類型
	Type string

	// StatusCode HTTP 狀態碼(如果是 API 錯誤)
	StatusCode int

	// Message 錯誤訊息
	Message string

	// ResponseBody API 回應體(如果是 API 錯誤)
	ResponseBody string

	// Err 原始錯誤
	Err error

	// URL webhook URL(用於上下文)
	URL string

	// ErrorCode 具體的錯誤代碼(用於更細緻的分類)
	ErrorCode string
}

WebhookError 表示 webhook 操作中的錯誤

func NewAPIError

func NewAPIError(url string, statusCode int, responseBody string) *WebhookError

NewAPIError 創建 API 錯誤

func NewNetworkError

func NewNetworkError(url string, err error) *WebhookError

NewNetworkError 創建網路錯誤,自動分類錯誤類型

func NewSerializationError

func NewSerializationError(err error) *WebhookError

NewSerializationError 創建序列化錯誤

func (*WebhookError) DetailedMessage

func (e *WebhookError) DetailedMessage() string

DetailedMessage 返回詳細的錯誤訊息(多行格式)

func (*WebhookError) Error

func (e *WebhookError) Error() string

Error 實現 error 介面,提供詳細的錯誤訊息

func (*WebhookError) GetErrorCode

func (e *WebhookError) GetErrorCode() string

GetErrorCode 返回錯誤代碼

func (*WebhookError) GetResponseBody

func (e *WebhookError) GetResponseBody() string

GetResponseBody 返回 API 回應體(如果是 API 錯誤)

func (*WebhookError) GetStatusCode

func (e *WebhookError) GetStatusCode() int

GetStatusCode 返回 HTTP 狀態碼(如果是 API 錯誤)

func (*WebhookError) IsAPIError

func (e *WebhookError) IsAPIError() bool

IsAPIError 判斷是否為 API 錯誤

func (*WebhookError) IsNetworkError

func (e *WebhookError) IsNetworkError() bool

IsNetworkError 判斷是否為網路錯誤

func (*WebhookError) IsSerializationError

func (e *WebhookError) IsSerializationError() bool

IsSerializationError 判斷是否為序列化錯誤

func (*WebhookError) Unwrap

func (e *WebhookError) Unwrap() error

Unwrap 返回原始錯誤(支援 errors.Unwrap)

Jump to

Keyboard shortcuts

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