unionewrapper

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

UniOne Go net/http 1.1.2

Web API 1.90

Quickstart guide: Send emails with Go · Docs for LLMs: llms.txt · API reference

Go net/http integration of the UniOne Go SDK (github.com/unione-repo/unione-go-sdk): the API client in the request context (net/http middleware), a webhook endpoint with signature check.

Install

go get github.com/unione-repo/unione-nethttp

Requirements: Go 1.21+.

Get an API key

  1. Sign up at cp.unione.io.
  2. Copy your API key from Settings → Security → API.
  3. Put it in an environment variable:
export UNIONE_API_KEY="your-api-key"

The package reads it from UNIONE_API_KEY (see the configuration below).

Server-side only. Use this package in backend code: API routes, server functions, workers. Never ship the API key to a browser or a mobile app, and never commit it.

Configuration

Settings are read from the environment by default:

UNIONE_API_KEY=YOUR_API_KEY
UNIONE_HOST=us1.unione.io
Option Environment variable Default Description
APIKey UNIONE_API_KEY User or project API key (required).
Host UNIONE_HOST api.unione.io API host (datacenter: api.unione.io, eu1.unione.io, us1.unione.io) or a full base URL.
Timeout UNIONE_TIMEOUT 30 Request timeout, seconds.
WebhookKey UNIONE_WEBHOOK_KEY API key the webhooks are signed with (the key of the user/project of the webhook), if it differs from the API key.
WebhookPath UNIONE_WEBHOOK_PATH /unione/webhook Path of the webhook endpoint.

ConfigFromEnv() reads the variables; a Config can also be filled in code. UNIONE_TIMEOUT is in seconds, Config.Timeout is a time.Duration.

Send your first email — no DNS setup

Every account can send test email right away from a sandbox domain: pre-verified, DKIM and SPF already set. It delivers only to addresses you confirm.

The examples use the API client of the package (see the configuration above).

1. Get your sandbox domain (domain/get-sandbox-domain). The call creates the domain on first use and returns the same one afterwards.

import (
	"fmt"
	"net/http"

	unionewrapper "github.com/unione-repo/unione-nethttp"
)

mux.HandleFunc("/sandbox-domain", func(w http.ResponseWriter, r *http.Request) {
	client := unionewrapper.ClientFromContext(r.Context())
	response, err := client.Domain.GetSandboxDomain(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	fmt.Fprintln(w, response.Domain)
})

2. Confirm your inbox (confirmed-email/create). UniOne sends a confirmation email; click the link in it within 48 hours.

import (
	"fmt"
	"net/http"

	"github.com/unione-repo/unione-go-sdk/api/confirmedemail"
	unionewrapper "github.com/unione-repo/unione-nethttp"
)

mux.HandleFunc("/confirm-email", func(w http.ResponseWriter, r *http.Request) {
	client := unionewrapper.ClientFromContext(r.Context())
	response, err := client.ConfirmedEmail.Create(r.Context(), &confirmedemail.ConfirmedEmailRequest{
		Email: "you@example.com",
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	fmt.Fprintln(w, response.Status)
})

Check the status with confirmed-email/list — your address should show "status": "confirmed".

3. Send the email (email/send) from any address on the sandbox domain to the confirmed address.

import (
	"fmt"
	"net/http"

	unione "github.com/unione-repo/unione-go-sdk"
	"github.com/unione-repo/unione-go-sdk/api/email"
	"github.com/unione-repo/unione-go-sdk/common"
	unionewrapper "github.com/unione-repo/unione-nethttp"
)

mux.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {
	client := unionewrapper.ClientFromContext(r.Context())
	response, err := client.Email.Send(r.Context(), &email.EmailSendRequest{
		Message: &email.MessageObject{
			Recipients: []email.MessageObjectRecipientsItem{
				{
					Email: "you@example.com",
				},
			},
			Body: &common.BodyObject{
				HTML: unione.String("<p>It works!</p>"),
			},
			Subject:   "Hello from UniOne",
			FromEmail: unione.String("noreply@<sandbox-domain>"),
		},
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	fmt.Fprintln(w, response.JobID)
})
What you get back
{
  "status": "success",
  "job_id": "1ZymBc-00041N-9X",
  "emails": [
    "you@example.com"
  ]
}

On error the API returns status: "error", a message and a numeric code:

{
  "status": "error",
  "code": 102,
  "message": "Error ID:83274F98-C7D5-11F1-B221-6214FF8707B1. Can not decode key wrongkey"
}
Same flow with curl
BASE=https://api.unione.io/en/transactional/api/v1

curl -s -X POST $BASE/domain/get-sandbox-domain.json \
  -H "Content-Type: application/json" -H "X-API-KEY: $UNIONE_API_KEY" -d '{}'

curl -s -X POST $BASE/confirmed-email/create.json \
  -H "Content-Type: application/json" -H "X-API-KEY: $UNIONE_API_KEY" \
  -d '{"email": "you@example.com"}'

curl -s -X POST $BASE/email/send.json \
  -H "Content-Type: application/json" -H "X-API-KEY: $UNIONE_API_KEY" \
  -d '{
        "message": {
          "recipients": [
            {
              "email": "you@example.com"
            }
          ],
          "from_email": "noreply@<sandbox-domain>",
          "subject": "Hello from UniOne",
          "body": {
            "html": "<p>It works!</p>"
          }
        }
      }'

Webhooks

The endpoint answers GET with 200 OK (the URL check of webhook/set) and accepts the POST notifications: it checks the auth field (MD5 of the request body in which the auth value is replaced by the API key), answers 401 to a wrong signature, and passes the notification and each of its events to the application.

import (
	"context"
	"log"

	"github.com/unione-repo/unione-go-sdk/api/webhook"
	unionewrapper "github.com/unione-repo/unione-nethttp"
)

cfg := unionewrapper.ConfigFromEnv()
handler := unionewrapper.WebhookHandler(cfg.SigningKey(), unionewrapper.Handlers{
	OnEvent: func(ctx context.Context, e *webhook.WebhookCallbackEventsByUserItemEventsItem, user *webhook.WebhookCallbackEventsByUserItem) error {
		if e.EventData != nil {
			log.Printf("UniOne event %s: %s %s", e.EventName, e.EventData.Email, e.EventData.Status)
		}
		return nil
	},
})

mux.Handle(cfg.Path(), handler)           // net/http, chi: r.Handle(cfg.Path(), handler)
router.Any(cfg.Path(), gin.WrapH(handler)) // gin
e.Any(cfg.Path(), echo.WrapHandler(handler)) // echo

Register the URL of the endpoint with webhook/set, e.g. https://example.com/unione/webhook.

API client

Every section of the API is available on the client, see the SDK docs.

import (
	"fmt"
	"net/http"

	unionewrapper "github.com/unione-repo/unione-nethttp"
)

cfg := unionewrapper.ConfigFromEnv()
client := cfg.Client()

mux := http.NewServeMux()
mux.HandleFunc("/usage", func(w http.ResponseWriter, r *http.Request) {
	info, err := unionewrapper.ClientFromContext(r.Context()).System.Info(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	fmt.Fprintln(w, info.Email)
})
http.ListenAndServe(":8080", unionewrapper.ClientMiddleware(client)(mux))

Sending through the API

The client calls email/send with all of its options: templates, substitutions, metadata, tracking. Fields of the request and other examples: Go SDK docs.

import (
	"fmt"
	"net/http"

	unione "github.com/unione-repo/unione-go-sdk"
	"github.com/unione-repo/unione-go-sdk/api/email"
	"github.com/unione-repo/unione-go-sdk/common"
	unionewrapper "github.com/unione-repo/unione-nethttp"
)

mux.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {
	client := unionewrapper.ClientFromContext(r.Context())
	response, err := client.Email.Send(r.Context(), &email.EmailSendRequest{
		Message: &email.MessageObject{
			Recipients: []email.MessageObjectRecipientsItem{
				{
					Email: "user@example.com",
					Substitutions: map[string]string{
						"CustomerId": "12452",
						"to_name":    "John Smith",
					},
				},
			},
			Body: &common.BodyObject{
				HTML:      unione.String("<b>Hello, {{to_name}}</b>"),
				Plaintext: unione.String("Hello, {{to_name}}"),
			},
			Subject:   "UniOne test email ",
			FromEmail: unione.String("email@example.com"),
			FromName:  unione.String("John Smith"),
		},
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	fmt.Fprintln(w, response.JobID)
})

Sandbox limits

  • Sends only to confirmed addresses: up to 10 per account.
  • Up to 100 emails a day.
  • The sandbox domain expires after 31 days; call domain/get-sandbox-domain again to get a new one.
  • Works only with the account API key, not a project key.
  • Not listed in domain/list; the other domain/* methods do not apply to it.

The sandbox is for development and testing. Do not use a sandbox domain as the sender in production.

Before production: verify your domain

  1. domain/get-dns-records — returns the values for your DNS records.

  2. Add these records at your DNS provider (the domain page of the control panel shows them too):

    Type Host Value
    TXT @ the verification-record value (unione-validate-hash=…)
    TXT <selector>._domainkey (the selector is on the domain page of the control panel, e.g. us) v=DKIM1; k=rsa; p=<dkim>
    TXT @ v=spf1 include:spf.unione.io ~all
    CNAME _dmarc the dmarc value
  3. domain/validate-verification-record, then domain/validate-dkim.

  4. domain/list — wait until the verification record is confirmed and DKIM is active.

  5. Read from_email from your config, so switching from the sandbox needs no code change.

Sending reliably

  • Retries: set message.idempotence_key on sends that may be retried, so a repeated request does not send twice.
  • Limits: up to 500 recipients and 10 MB per request; each attachment up to 7 MB.
  • Body: always include body.html or body.plaintext.
  • Delivery status: register a webhook (webhook/set) with a fast, idempotent HTTPS handler instead of polling.
  • Defaults: keep the default unsubscribe footer and tracking; changing them requires UniOne support.
  • Errors: retry 429 and 5xx with backoff; do not retry other errors unchanged.

For package contributors

See AGENTS.md: how this package is generated from the OpenAPI spec, built, tested and released.

Documentation

Overview

Package unionewrapper plugs the UniOne Go SDK into net/http applications: the client configured from the environment, a middleware that puts it into the request context and the webhook endpoint.

Index

Constants

View Source
const (
	EnvAPIKey      = "UNIONE_API_KEY"
	EnvHost        = "UNIONE_HOST"
	EnvTimeout     = "UNIONE_TIMEOUT"
	EnvWebhookKey  = "UNIONE_WEBHOOK_KEY"
	EnvWebhookPath = "UNIONE_WEBHOOK_PATH"
)

Environment variables read by ConfigFromEnv.

View Source
const DefaultWebhookPath = "/unione/webhook"

DefaultWebhookPath is the path of the webhook endpoint when WebhookPath is empty.

View Source
const MaxWebhookBody = 16 << 20

MaxWebhookBody is the largest webhook request body accepted, bytes.

View Source
const Platform = "nethttp.1.1.2"

Platform is the package and its version in the "platform" query parameter of the requests, before the SDK one.

View Source
const SignaturePlaceholder = "00000000000000000000000000000000"

SignaturePlaceholder is the "auth" value Sign replaces.

Variables

View Source
var ErrNoAPIKey = errors.New("unionewrapper: " + EnvAPIKey + " is not set")

ErrNoAPIKey is returned by NewClientFromEnv when UNIONE_API_KEY is not set.

Functions

func ClientFromContext

func ClientFromContext(ctx context.Context) *unione.Client

ClientFromContext returns the API client of ClientMiddleware, nil when there is none.

func ClientMiddleware

func ClientMiddleware(c *unione.Client) func(http.Handler) http.Handler

ClientMiddleware puts the API client into the context of every request.

func NewClientFromEnv

func NewClientFromEnv() (*unione.Client, error)

NewClientFromEnv returns the API client configured from the environment.

func Sign

func Sign(body []byte, apiKey string) []byte

Sign signs a body whose "auth" is SignaturePlaceholder, e.g. for tests.

func VerifySignature

func VerifySignature(body []byte, apiKey string) bool

VerifySignature checks the "auth" field of a webhook notification: the MD5 of the request body in which the "auth" value is replaced by the API key of the user/project of the webhook.

func WebhookHandler

func WebhookHandler(key string, h Handlers) http.Handler

WebhookHandler is the webhook endpoint: GET/HEAD answer 200 (the URL check of webhook/set), POST checks the signature with key (401 when wrong), parses the notification and calls the handlers.

func WithClient

func WithClient(ctx context.Context, c *unione.Client) context.Context

WithClient returns a copy of ctx with the API client.

Types

type Config

type Config struct {
	// APIKey is the user or project API key.
	APIKey string
	// Host is an API host (datacenter) or a full base URL; empty: the default host.
	Host string
	// Timeout of the requests; 0: 30 seconds.
	Timeout time.Duration
	// WebhookKey is the API key the webhooks are signed with; empty: APIKey.
	WebhookKey string
	// WebhookPath is the path of the webhook endpoint; empty: DefaultWebhookPath.
	WebhookPath string
}

Config holds the settings of the client and of the webhook endpoint.

func ConfigFromEnv

func ConfigFromEnv() Config

ConfigFromEnv reads the configuration from the UNIONE_* environment variables (UNIONE_TIMEOUT is in seconds).

func (Config) Client

func (c Config) Client() *unione.Client

Client returns the API client for the configuration.

func (Config) Path

func (c Config) Path() string

Path is the path of the webhook endpoint: WebhookPath or DefaultWebhookPath.

func (Config) SigningKey

func (c Config) SigningKey() string

SigningKey is the key the webhooks are checked with: WebhookKey or APIKey.

type Handlers

type Handlers struct {
	// OnNotification gets the whole notification.
	OnNotification func(ctx context.Context, notification *webhook.WebhookCallback) error
	// OnEvent gets each event of the notification (email status, spam block...) with its user/project.
	OnEvent func(ctx context.Context, event *webhook.WebhookCallbackEventsByUserItemEventsItem, user *webhook.WebhookCallbackEventsByUserItem) error
}

Handlers receive the webhook notifications with a valid signature. Both are optional; an error answers 500, so the API repeats the notification later. They must be fast: the API waits for 200 OK for 3 seconds.

Jump to

Keyboard shortcuts

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