# Fiber

Send a Fiber app's mail with the Go SDK, take each webhook at a route that checks its signature, and develop against a test server.

The Go SDK, `sendora.se/go/sendora`, sends a Fiber app's mail through the API. Its `sendora.VerifyWebhook` checks each delivery's signature in a Fiber route. This guide's samples run on Fiber 3.7 with Go 1.27 or newer.

## Before you start

- A [server key](https://sendora.se/docs/keys), which you create on the server's **API keys** tab in the dashboard. A [test server](https://sendora.se/docs/test-servers)'s key works before Sendora approves your account, and it delivers nothing.
- A [verified sending domain](https://sendora.se/docs/domains) for the From address. A test server checks the domain too.

## Install

In your app's module, install Fiber and the SDK:

```sh
go get github.com/gofiber/fiber/v3 sendora.se/go/sendora
```

The samples below are the files of that module's `main` package.

## Settings

Set the server key and the webhook's secret in the environment that runs the app, and keep both out of git. You get the secret once you create the webhook, as [Webhooks](#webhooks) below shows.

```sh
export SENDORA_API_TOKEN=sk_…
export SENDORA_WEBHOOK_SECRET=whsec_…
```

`main.go` makes the client as the app starts, and serves the routes that the sections below write:

```go
package main

import (
	"cmp"
	"log"
	"net"
	"os"
	"time"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/middleware/logger"
	"github.com/gofiber/fiber/v3/middleware/recover"
	"sendora.se/go/sendora"
)

func main() {
	key := os.Getenv("SENDORA_API_TOKEN")
	production := os.Getenv("APP_ENV") == "production"
	if production && sendora.IsTestKey(key) {
		log.Fatal("SENDORA_API_TOKEN is a test key;" +
			" nothing would be delivered")
	}

	// It reads the same key, and fails without one.
	client, err := sendora.NewClientFromEnv()
	if err != nil {
		log.Fatal(err)
	}

	webhooks, err := webhookRoute(
		client,
		os.Getenv("SENDORA_WEBHOOK_SECRET"),
	)
	if err != nil {
		log.Fatal(err)
	}

	app := fiber.New(fiber.Config{
		// Sendora's largest webhook delivery.
		BodyLimit: 20 * 1024 * 1024,
		// Fiber sets no time limit of its own.
		ReadTimeout: 15 * time.Second,
		IdleTimeout: time.Minute,
	})
	app.Use(logger.New())
	app.Use(recover.New())
	app.Post("/contact", contact(client))
	app.Post("/sendora/webhook", webhooks)

	// Sendora posts only to HTTPS, so a proxy or a
	// tunnel in front serves this. If the proxy is on
	// another host or container, listen on ":"+port.
	port := cmp.Or(os.Getenv("PORT"), "8080")
	listener, err := net.Listen("tcp", "localhost:"+port)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Listening on", listener.Addr())
	log.Fatal(app.Listener(listener, fiber.ListenConfig{
		DisableStartupMessage: true,
	}))
}
```

- `sendora.NewClientFromEnv()` reads the key from `SENDORA_API_TOKEN`. Without a key, it returns an error, and the app stops before it listens.
- Make one client and share it. It is safe for use by many goroutines at once, and it keeps its connections between calls.
- Fiber's [`ReadTimeout` and `IdleTimeout`](https://github.com/gofiber/fiber/blob/v3.7.0/app.go#L319-L336) set no time limit unless you set them. So `main.go` sets both.
- Run it with `go run .`. It listens on `localhost:8080`, or on the port in `PORT`.

## Send mail

The handler in `contact.go` sends a contact form's message to your support address:

```go
package main

import (
	"log"
	"net/mail"

	"github.com/gofiber/fiber/v3"
	"sendora.se/go/sendora"
)

func contact(client *sendora.Client) fiber.Handler {
	return func(c fiber.Ctx) error {
		visitor, err := mail.ParseAddress(
			c.FormValue("email"),
		)
		message := c.FormValue("message")
		if err != nil || message == "" {
			return fiber.NewError(
				fiber.StatusBadRequest,
				"Send an address and a message.",
			)
		}

		email := sendora.Email{
			From: sendora.Address{
				Email: "no-reply@example.se",
				Name:  "Example AB",
			},
			To: []sendora.Address{
				{Email: "support@example.se"},
			},
			Headers: map[string]string{
				"Reply-To": visitor.Address,
			},
			Subject: "A message from the contact form",
			Text:    message,
			Tag:     "contact-form",
		}
		ctx := c.Context()
		accepted, err := client.Email.Send(ctx, email)
		if err != nil {
			log.Println("Sendora took no mail:", err)
			return fiber.NewError(
				fiber.StatusServiceUnavailable,
				"Try again later.",
			)
		}

		answer := fiber.Map{
			"messageId": accepted.MessageID,
		}
		return c.Status(fiber.StatusAccepted).JSON(answer)
	}
}
```

- The handler sends to your own address, and takes the visitor's only for `Reply-To`. A handler that sends to an address from its request would let anyone mail anyone.
- `mail.ParseAddress`, from Go's standard library, fails on a missing or malformed address. The handler then answers 400, as it does to a form without a message.
- Sendora refuses a header value that holds a line break, so the visitor's address cannot add a header of its own.
- `Send` returns the accepted message, with Sendora's `MessageID`, which the log and the webhooks use.
- The tag sets the form's mail apart in the log and in every webhook. Add [metadata](https://sendora.se/docs/sending#attachments-headers-tags-and-metadata) for ids of your own, such as an order's.
- If Sendora refuses the mail, `Send` returns a `*sendora.Error`, whose `Code` is the [error code](https://sendora.se/docs/errors). The handler logs it, and answers 503. The error's message holds no address and nothing of the mail.
- The SDK sends each mail under an [idempotency key](https://sendora.se/docs/sending#idempotency), so its own retries never send it twice. When a job may send the same mail twice, pass a key of your own, as in `client.Email.Send(ctx, email, sendora.WithIdempotencyKey("order-1042-shipped"))`. A retry with the same key returns the first answer and sends nothing.

## Webhooks

The webhook's route checks each delivery's signature, then handles its event. A delivery is one post of one event to your webhook.

1. Add the route, `webhooks.go`. This one logs a hard bounce, and files each received mail as [Received mail](#received-mail) explains:

```go
package main

import (
	"context"
	"errors"
	"log"

	"github.com/gofiber/fiber/v3"
	"sendora.se/go/sendora"
)

func webhookRoute(
	client *sendora.Client,
	secret string,
) (fiber.Handler, error) {
	// VerifyWebhook would refuse every delivery.
	if secret == "" {
		return nil, errors.New(
			"the webhook's signing secret is empty")
	}

	// An error gets a 500, and Sendora delivers the
	// event again.
	handle := func(
		ctx context.Context,
		event sendora.Event,
	) error {
		switch event := event.(type) {
		case *sendora.BouncedEvent:
			if event.Details.Hard {
				log.Println("A message bounced for good",
					event.MessageID)
			}
		case *sendora.InboundEvent:
			return fileTicket(
				ctx,
				client,
				event.InboundMessageID,
			)
		default:
			// Every other event, a newer one included.
		}
		return nil
	}

	return func(c fiber.Ctx) error {
		// The bytes that Sendora signed.
		event, err := sendora.VerifyWebhook(
			c.BodyRaw(),
			c.Get("Sendora-Signature"),
			secret,
		)
		if err != nil {
			return fiber.ErrBadRequest
		}

		err = handle(c.Context(), event)
		if err != nil {
			return err
		}
		return c.SendStatus(fiber.StatusNoContent)
	}, nil
}
```

2. Create a webhook under the server's [Webhooks](https://app.sendora.se/servers) tab, with the address of the route, such as `https://example.se/sendora/webhook`. If the app receives mail, create it through the API instead, as [Received mail](#received-mail) says.
3. Put its secret in `SENDORA_WEBHOOK_SECRET`, and deploy.

Fiber is not built on `net/http`, so the route checks each delivery itself. It passes [`c.BodyRaw()`](https://github.com/gofiber/fiber/blob/v3.7.0/req.go#L122-L127), the body as Sendora sent it, and the `Sendora-Signature` header to `sendora.VerifyWebhook`. That function checks the signature before it parses anything. Then it returns the event, as a type of its own such as `*sendora.BouncedEvent`, so its `Details` are typed. [Webhooks](https://sendora.se/docs/webhooks#events) says when Sendora sends each event, and [Webhook events](https://sendora.se/docs/api/webhook-events) lists their fields.

- The route answers 204 when your function returns nil. When your function returns an error, the route answers 500, and Sendora delivers the event again later, on the schedule that [Webhooks](https://sendora.se/docs/webhooks#retries-dead-letters-and-replay) gives.
- The route returns that error to Fiber, whose logger writes it on the request's line.
- Sendora waits only as long as [Limits](https://sendora.se/docs/limits#webhooks) says, so hand slow work to a queue.
- A delivery whose signature is missing, wrong or more than five minutes old gets 400, and your function never sees it.
- Without the secret, `webhookRoute` returns an error, and the app stops as it starts.
- A delivery can arrive more than once. Key your handling on the event's `ID`, the delivery's id, which stays the same on each attempt.
- An event newer than your release of the SDK comes as an `*sendora.UnknownEvent`, which the type switch's `default` takes. So the route answers 204 to it.
- The route takes the largest delivery that [Limits](https://sendora.se/docs/limits#webhooks) gives, so an `inbound` event with its content fits. A proxy in front of the app may allow less, so allow the route that size there too.
- Fiber's [`BodyLimit`](https://github.com/gofiber/fiber/blob/v3.7.0/app.go#L279-L283) refuses a larger body before any route runs, and its default is lower than that size. So `main.go` raises it, for every route of the app.
- If the app checks a CSRF token or a session in a middleware, register the webhook's route outside it. Sendora sends neither.
- To [roll the secret](https://sendora.se/docs/webhooks#roll-the-secret), create the new one, set `SENDORA_WEBHOOK_SECRET` to it and restart the app, which reads the secret as it starts. Sendora signs each delivery with both until you delete the old one.

## Received mail

The route above files each received mail. An `inbound` event has the message's `InboundMessageID`, and `tickets.go` fetches the mail by it:

```go
package main

import (
	"context"
	"os"
	"path/filepath"

	"sendora.se/go/sendora"
)

func fileTicket(
	ctx context.Context,
	client *sendora.Client,
	inboundMessageID string,
) error {
	mail, err := client.Inbound.Get(ctx, inboundMessageID)
	if err != nil {
		return err
	}

	// Only a DMARC pass proves the From domain sent it.
	folder := "tickets"
	dmarc := mail.Authentication.DMARC
	if dmarc != sendora.AuthVerdictPass {
		folder = filepath.Join(folder, "unverified")
	}
	err = os.MkdirAll(folder, 0o750)
	if err != nil {
		return err
	}

	text := ""
	if mail.Text != nil {
		text = *mail.Text
	}
	name := filepath.Join(folder, inboundMessageID+".txt")
	return os.WriteFile(name, []byte(text), 0o600)
}
```

- The route fetches the mail, so create its webhook through the API with `InboundContent` set to `sendora.InboundContentReference`. A webhook from the dashboard carries the whole mail in each `inbound` event, as [Inbound](https://sendora.se/docs/inbound#the-inbound-event) explains.
- Only a DMARC `pass` proves that the From domain sent the message. With any other verdict, the From address may be forged.
- Sendora keeps the mail's content for the stream's retention, as [Inbound](https://sendora.se/docs/inbound#what-sendora-keeps) says. After that, the route finds its `Text` nil.
- A test server has no inbound stream, so receive mail on a live server.

## Develop against a test server

A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with `sk_test_`.

1. Create a test server under [Servers › New server](https://app.sendora.se/servers/new), with **Testserver** ticked, and a key on its **API keys** tab.
2. Put the key in `SENDORA_API_TOKEN` on your machine, and in CI. Keep a live server's key in production.
3. Send to the [simulator's addresses](https://sendora.se/docs/test-servers#the-simulators-addresses), such as `hardbounce@simulator.sendora.se`, to act out a bounce or a complaint. The message's events show in the dashboard's message log, as [Messages and events](https://sendora.se/docs/messages) explains.

`main.go` above refuses a test key where mail must arrive. With `APP_ENV` set to `production`, the app stops before it listens. Without `APP_ENV`, the check lets any key through, so set it on every production machine. Leave it unset on your machine, in CI and on staging, which can then send with a test key.

Sendora posts webhooks only to a public HTTPS address, so a test server's events cannot reach your machine. Test the routes with the SDK's package `sendoratest` instead. Its stand-in Sendora answers the client in memory and records each send. Its signed examples of each event reach the webhook's route as Sendora posts them. `main_test.go` tests both routes:

```go
package main

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"github.com/gofiber/fiber/v3"
	"sendora.se/go/sendora"
	"sendora.se/go/sendora/sendoratest"
)

func TestTheFormMailsSupport(t *testing.T) {
	stub := sendoratest.NewServer(t)
	app := fiber.New()
	app.Post("/contact", contact(stub.Client()))

	form := url.Values{
		"email":   {"anna@example.com"},
		"message": {"Where is my order?"},
	}
	request := httptest.NewRequest(http.MethodPost,
		"/contact", strings.NewReader(form.Encode()))
	request.Header.Set(fiber.HeaderContentType,
		fiber.MIMEApplicationForm)
	response, err := app.Test(request)
	if err != nil {
		t.Fatal(err)
	}

	sent := stub.Sent()
	if response.StatusCode != http.StatusAccepted ||
		len(sent) != 1 {
		t.Fatalf("answered %d", response.StatusCode)
	}
	headers := sent[0].Emails[0].Headers
	if headers["Reply-To"] != "anna@example.com" {
		t.Errorf("Reply-To is %q", headers["Reply-To"])
	}
}

func TestTheWebhookTakesASignedBounce(t *testing.T) {
	const secret = "whsec_test"

	stub := sendoratest.NewServer(t)
	route, err := webhookRoute(stub.Client(), secret)
	if err != nil {
		t.Fatal(err)
	}
	app := fiber.New()
	app.Post("/sendora/webhook", route)

	body := sendoratest.EventJSON(
		sendora.WebhookEventNameBounced,
	)
	request := sendoratest.WebhookRequest(
		"/sendora/webhook", body, secret)
	response, err := app.Test(request)
	if err != nil {
		t.Fatal(err)
	}

	if response.StatusCode != http.StatusNoContent {
		t.Errorf("answered %d", response.StatusCode)
	}
}
```

Run it with `go test ./...`. The tests need no key or secret in the environment, and they send nothing.
