# Gin

Send a Gin 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 Gin app's mail through the API. Its webhook handler checks each delivery's signature, and Gin serves it as a route. This guide's samples run on Gin 1.12 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 Gin and the SDK:

```sh
go get github.com/gin-gonic/gin 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"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"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)
	}

	router := gin.Default()
	router.POST("/contact", contact(client))
	router.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())

	// Gin's router.Run sets no time limit at all.
	server := &http.Server{
		Handler:           router,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		IdleTimeout:       time.Minute,
	}
	log.Fatal(server.Serve(listener))
}
```

- `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.
- Gin's [`router.Run`](https://github.com/gin-gonic/gin/blob/v1.12.0/gin.go#L540-L556) serves on an `http.Server` that sets no time limit at all. So the app serves the router on a server of its own, with the three limits set.
- 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 (
	"net/http"

	"github.com/gin-gonic/gin"
	"sendora.se/go/sendora"
)

type contactForm struct {
	Email   string `form:"email" binding:"required,email"`
	Message string `form:"message" binding:"required"`
}

func contact(client *sendora.Client) gin.HandlerFunc {
	return func(c *gin.Context) {
		var form contactForm
		if err := c.ShouldBind(&form); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": "Send an address and a message.",
			})
			return
		}

		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": form.Email,
			},
			Subject: "A message from the contact form",
			Text:    form.Message,
			Tag:     "contact-form",
		}
		ctx := c.Request.Context()
		accepted, err := client.Email.Send(ctx, email)
		if err != nil {
			// Gin's logger writes the error's code.
			_ = c.Error(err)
			c.JSON(http.StatusServiceUnavailable, gin.H{
				"error": "Try again later.",
			})
			return
		}

		c.JSON(http.StatusAccepted, gin.H{
			"messageId": accepted.MessageID,
		})
	}
}
```

- 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.
- `ShouldBind` reads the form's fields. It fails on a form without an address or a message, or with a malformed address, as the `binding` tags say. The handler then answers 400.
- 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). `c.Error` hands it to Gin's logger, which writes the code on the request's line. 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"
	"log"

	"github.com/gin-gonic/gin"
	"sendora.se/go/sendora"
)

func webhookRoute(
	client *sendora.Client,
	secret string,
) (gin.HandlerFunc, error) {
	// 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
	}

	// Without the secret, it returns an error.
	webhooks, err := sendora.NewWebhookHandler(
		secret,
		handle,
	)
	if err != nil {
		return nil, err
	}
	return gin.WrapH(webhooks), 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.

[`gin.WrapH`](https://github.com/gin-gonic/gin/blob/v1.12.0/utils.go#L53-L58) turns the SDK's `http.Handler` into a Gin route. That handler reads the body as Sendora sent it, and checks its signature before it parses anything. Then it calls your function with 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.
- 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.
- 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/gin-gonic/gin"
	"sendora.se/go/sendora"
	"sendora.se/go/sendora/sendoratest"
)

func TestTheFormMailsSupport(t *testing.T) {
	stub := sendoratest.NewServer(t)
	router := gin.New()
	router.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("Content-Type",
		"application/x-www-form-urlencoded")
	recorder := httptest.NewRecorder()
	router.ServeHTTP(recorder, request)

	sent := stub.Sent()
	if recorder.Code != http.StatusAccepted ||
		len(sent) != 1 {
		t.Fatalf("answered %d", recorder.Code)
	}
	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)
	}
	router := gin.New()
	router.POST("/sendora/webhook", route)

	body := sendoratest.EventJSON(
		sendora.WebhookEventNameBounced,
	)
	request := sendoratest.WebhookRequest(
		"/sendora/webhook", body, secret)
	recorder := httptest.NewRecorder()
	router.ServeHTTP(recorder, request)

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

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