go-notificationgo-notification
Examples

Basic Example

A complete, runnable program that sends one email via Mailgun.

This is the smallest useful program — no frameworks, no extras. Drop it into main.go, set one env var, and it runs.

Examples live in their own Go module

The runnable version of this program is in _examples/basic of the repository. The _examples/ directory is a separate Go module, so the library itself keeps zero third-party dependencies. Run it from there: cd _examples && go run ./basic.

main.go

main.go
package main

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

    notification "github.com/gopackx/go-notification"
    "github.com/gopackx/go-notification/channel/mail"
    "github.com/gopackx/go-notification/channel/mail/mailgun"
)

type User struct {
    ID    int64
    Email string
}

func (u User) GetID() string { return strconv.FormatInt(u.ID, 10) }

func (u User) RouteNotificationFor(channel string) string {
    if channel == "mail" {
        return u.Email
    }
    return ""
}

type OrderShipped struct {
    OrderID string
}

func (n OrderShipped) Via(u notification.Notifiable) []string {
    return []string{"mail"}
}

func (n OrderShipped) ToMail(u notification.Notifiable) *mail.Message {
    return mail.NewMessage().
        SetSubject("Your order has shipped").
        SetGreeting("Hi there,").
        Line("Your order " + n.OrderID + " is on its way.").
        Action("Track package", "https://example.com/track/"+n.OrderID).
        Line("Thanks for shopping with us.")
}

func main() {
    notifier := notification.New(notification.Config{})

    notifier.RegisterChannel(mailgun.New(mailgun.Config{
        Domain: "mg.example.com",
        APIKey: os.Getenv("MAILGUN_API_KEY"),
        From:   mail.Address{Name: "Acme", Address: "noreply@example.com"},
    }))

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

    user := User{ID: 1, Email: "customer@example.com"}

    if err := notifier.Send(ctx, user, OrderShipped{OrderID: "A-1024"}); err != nil {
        log.Fatalf("send failed: %v", err)
    }

    // Give the async worker a moment to flush before the program exits.
    notifier.Close()
    log.Println("done")
}

Run it

From a clone of the repository:

terminal.sh
export MAILGUN_API_KEY=key-xxxx
cd _examples && go run ./basic

Or, if you pasted the code into your own module, go run . in that directory.

What's happening

  1. notification.New() spins up a worker pool with sane defaults — async sends, exponential-backoff retries.
  2. RegisterChannel(...) wires up one driver; its name comes from the driver's Name() (here, "mail").
  3. Send() calls OrderShipped.Via() to get channel names, then for each one calls ToMail() to build the message and dispatches to the Mailgun driver.
  4. Close() waits for in-flight sends to finish. Without it, a short program may exit before the async send completes.

Next