notifier

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: MIT Imports: 11 Imported by: 0

README

notifier

Build Tests Lint Go Reference Coverage Status

A small, zero-dependency Go library that fans a single message out to multiple notification channels concurrently. Useful for alerting, build pipelines, personal automations, and anywhere you want one call to reach DingTalk, Bark, Telegram, etc. without writing five HTTP clients.

Providers

Provider Package
DingTalk provider/dingtalk
Bark provider/bark
Lark provider/lark
Feishu provider/feishu
Server 酱 provider/serverchan
WeCom (企业微信) provider/wecom
Telegram Bot provider/telegram

Install

go get github.com/moond4rk/notifier

Requires Go 1.26 or later.

Quickstart

package main

import (
    "context"
    "log"
    "os"
    "time"

    "github.com/moond4rk/notifier"
)

func main() {
    n := notifier.New(
        notifier.WithDingTalk(os.Getenv("DINGTALK_TOKEN"), os.Getenv("DINGTALK_SECRET")),
        notifier.WithBark(os.Getenv("BARK_KEY"), ""),
        notifier.WithTelegram(os.Getenv("TELEGRAM_TOKEN"), os.Getenv("TELEGRAM_CHAT_ID")),
    )

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    if err := n.Send(ctx, notifier.Message{
        Subject: "build failed",
        Content: "main.go:42 syntax error",
    }); err != nil {
        log.Print(err)
    }
}

A failure in one provider does not silence the rest — Send returns a *notifier.MultiError that wraps each per-provider failure as a *notifier.SendError. errors.As and errors.Is work as you'd expect:

var multi *notifier.MultiError
if errors.As(err, &multi) {
    for _, e := range multi.Errors {
        log.Printf("%s: %v", e.Provider, e.Err)
    }
}

Channel-specific options (Extras)

Message.Extras is a map[string]any of provider-specific keys. Unknown keys are silently ignored, so it is safe to set them when broadcasting to a mixed list of providers.

import (
    "github.com/moond4rk/notifier"
    "github.com/moond4rk/notifier/provider/bark"
    "github.com/moond4rk/notifier/provider/dingtalk"
    "github.com/moond4rk/notifier/provider/telegram"
)

n.Send(ctx, notifier.Message{
    Subject: "alarm",
    Content: "fire in srv-01",
    Format:  notifier.FormatMarkdown,
    Extras: map[string]any{
        bark.KeySound:               "siren.caf",
        bark.KeyGroup:               "alerts",
        dingtalk.KeyAtAll:           true,
        telegram.KeyDisableNotification: false,
    },
})
Provider Key constant Type Effect
bark KeySound string Override notification sound
bark KeyIcon string Custom icon URL
bark KeyGroup string Group key
bark KeyURL string Tap-to-open URL
bark KeyBadge int Badge count
dingtalk KeyAtAll bool @-everyone
dingtalk KeyAtMobiles []string @ by phone number
dingtalk KeyAtUserIDs []string @ by user ID
wecom KeyMentionedList []string @ by username (text mode)
wecom KeyMentionedMobile []string @ by phone (text mode)
telegram KeyDisableNotification bool Silent message
telegram KeyDisableWebPagePreview bool No link preview

Custom providers

Implement the notifier.Provider interface (alias of provider.Provider) and register with WithProvider:

type slackProvider struct{ webhook string }

func (slackProvider) Name() string { return "slack" }

func (s slackProvider) Send(ctx context.Context, msg notifier.Message) error {
    // POST to s.webhook with ctx; return error on failure.
    return nil
}

n := notifier.New(notifier.WithProvider(slackProvider{webhook: "..."}))

HTTP client and timeouts

Each built-in provider uses an *http.Client with a 30-second timeout by default. To share a client (for connection pooling, proxies, custom transports, ...), pass it through WithHTTPClient before the convenience helpers:

client := &http.Client{Timeout: 5 * time.Second}
n := notifier.New(
    notifier.WithHTTPClient(client),         // must come first
    notifier.WithDingTalk(token, secret),
    notifier.WithBark(key, ""),
)

Or set it per provider via the Config struct when constructing manually:

notifier.WithProvider(dingtalk.New(dingtalk.Config{
    Token: token, Secret: secret, HTTPClient: client,
}))

License

MIT — see LICENSE.

Documentation

Overview

Package notifier dispatches a single message to multiple notification channels concurrently.

A Notifier is constructed with one or more provider options and then used to broadcast a Message:

n := notifier.New(
    notifier.WithDingTalk(os.Getenv("DINGTALK_TOKEN"), os.Getenv("DINGTALK_SECRET")),
    notifier.WithBark(os.Getenv("BARK_KEY"), ""),
)
if err := n.Send(ctx, notifier.Message{
    Subject: "alert",
    Content: "the disk is full",
}); err != nil {
    log.Print(err)
}

Each provider runs in its own goroutine; failures are aggregated into a *MultiError so a single broken channel does not silence the others.

Channel-specific options (Bark sound, Lark markdown, ...) travel via Message.Extras using string keys defined in the corresponding provider package.

Custom providers

Anything that implements provider.Provider can be registered with WithProvider. The provider package documents the contract.

Index

Constants

View Source
const FormatMarkdown = provider.FormatMarkdown

FormatMarkdown signals the message body uses Markdown.

View Source
const FormatText = provider.FormatText

FormatText is plain text, the default Format.

Variables

View Source
var ErrNoProvider = provider.ErrNoProvider

ErrNoProvider is returned by Send when no providers are configured.

Functions

This section is empty.

Types

type Format added in v0.3.0

type Format = provider.Format

Format is an alias of provider.Format, describing the wire format of Message.Content.

type Message added in v0.3.0

type Message = provider.Message

Message is an alias of provider.Message — the payload broadcast to providers.

type MultiError added in v0.3.0

type MultiError = provider.MultiError

MultiError is an alias of provider.MultiError aggregating per-provider failures from a single Send call.

type Notifier

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

Notifier dispatches a Message to all configured providers concurrently. Use New to construct one and Send to deliver a message.

func New

func New(options ...Option) *Notifier

New returns a Notifier configured by the supplied options.

func (*Notifier) HTTPClient added in v0.3.0

func (n *Notifier) HTTPClient() *http.Client

HTTPClient returns the shared *http.Client used by convenience helpers such as WithDingTalk to construct providers. Returns nil if WithHTTPClient was never called; provider packages then fall back to their own default client.

func (*Notifier) Providers

func (n *Notifier) Providers() []Provider

Providers returns a copy of the configured providers slice.

func (*Notifier) Send

func (n *Notifier) Send(ctx context.Context, msg Message) error

Send dispatches msg to every configured provider concurrently. It returns:

  • ErrNoProvider if no providers are configured
  • *MultiError if at least one provider failed; successful providers are not reported
  • nil if all providers succeeded

ctx is forwarded unchanged to each provider; cancelling it aborts every in-flight request. A failure in one provider does not prevent the others from running.

type Option

type Option func(*Notifier)

Option configures a Notifier. Options are applied in order, so WithHTTPClient must precede any WithXxx convenience helper that should use the shared client.

func WithBark

func WithBark(key, server string) Option

WithBark registers a Bark provider. server is the host (e.g. "api.day.app"); pass an empty string to use the public default.

func WithDingTalk

func WithDingTalk(token, secret string) Option

WithDingTalk registers a DingTalk webhook provider with the given access token and (optional) secret.

func WithFeishu

func WithFeishu(token, secret string) Option

WithFeishu registers a Feishu webhook provider.

func WithHTTPClient added in v0.3.0

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the *http.Client used by the convenience helpers (WithDingTalk, WithBark, ...) when they construct providers. Providers added via WithProvider keep whatever client they were configured with.

func WithLark

func WithLark(token, secret string) Option

WithLark registers a Lark webhook provider.

func WithProvider added in v0.3.0

func WithProvider(p Provider) Option

WithProvider registers a Provider. A nil Provider is silently ignored so callers can pass the result of pkg.New directly even when its required field is empty.

func WithServerChan added in v0.1.1

func WithServerChan(userID, sendKey string) Option

WithServerChan registers a Server 酱 provider. userID may be empty for the modern SCT API.

func WithTelegram added in v0.3.0

func WithTelegram(token, chatID string) Option

WithTelegram registers a Telegram bot provider. token is the bot token from @BotFather; chatID is the destination chat (numeric or "@channel" form).

func WithWeCom added in v0.3.0

func WithWeCom(key string) Option

WithWeCom registers a WeCom (企业微信) group robot provider. key is the value of the "key" query parameter on the bot's webhook URL.

type Provider added in v0.3.0

type Provider = provider.Provider

Provider is an alias of provider.Provider, the interface every channel implements. Anything implementing it can be registered with WithProvider.

type SendError added in v0.3.0

type SendError = provider.SendError

SendError is an alias of provider.SendError, returned per-provider in a MultiError.

Directories

Path Synopsis
examples
basic command
Basic broadcast example: send a single message to every configured channel concurrently.
Basic broadcast example: send a single message to every configured channel concurrently.
internal
httpx
Package httpx provides a small HTTP helper shared by all notifier providers.
Package httpx provides a small HTTP helper shared by all notifier providers.
Package provider defines the Provider interface that every notifier channel implements, plus the shared Message and error types.
Package provider defines the Provider interface that every notifier channel implements, plus the shared Message and error types.
bark
Package bark implements a notifier.Provider for the Bark iOS app (https://day.app/).
Package bark implements a notifier.Provider for the Bark iOS app (https://day.app/).
dingtalk
Package dingtalk implements a notifier.Provider for DingTalk group robots (https://open.dingtalk.com/).
Package dingtalk implements a notifier.Provider for DingTalk group robots (https://open.dingtalk.com/).
feishu
Package feishu implements a notifier.Provider for Feishu custom bots (https://www.feishu.cn/).
Package feishu implements a notifier.Provider for Feishu custom bots (https://www.feishu.cn/).
lark
Package lark implements a notifier.Provider for Lark custom bots (https://www.larksuite.com/).
Package lark implements a notifier.Provider for Lark custom bots (https://www.larksuite.com/).
serverchan
Package serverchan implements a notifier.Provider for Server 酱 (https://sct.ftqq.com/).
Package serverchan implements a notifier.Provider for Server 酱 (https://sct.ftqq.com/).
telegram
Package telegram implements a notifier.Provider for Telegram Bot API (https://core.telegram.org/bots/api#sendmessage).
Package telegram implements a notifier.Provider for Telegram Bot API (https://core.telegram.org/bots/api#sendmessage).
wecom
Package wecom implements a notifier.Provider for WeCom (企业微信) group robots (https://developer.work.weixin.qq.com/document/path/91770).
Package wecom implements a notifier.Provider for WeCom (企业微信) group robots (https://developer.work.weixin.qq.com/document/path/91770).

Jump to

Keyboard shortcuts

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