Gin project: a complete REST API · 5 MIN READ
Start from validated configuration and wire the whole service in one composition root
Load and validate configuration from the environment, fail fast with every problem listed, and wire store, service, handlers, engine and http.Server with signal-driven shutdown.
The last piece of the notes API is the code that runs first. A typo in an environment variable should stop a deploy with a clear message, not start a server with a default timeout, a debug-mode router or a proxy list that trusts the whole internet. This lesson builds the configuration loader, then assembles every package from the earlier lessons in cmd/api/main.go.
gin · A MAP OF THE IDEA
- Load and validate config
- Wire store to engine
- Bind listener, serve
- Signal, drain, exit
Useful when
- Bad deployments fail before serving, with every problem listed.
- All wiring is in one short function that names every dependency.
- Shutdown has one owner and one budget taken from configuration.
Watch out
- URL.Redacted masks only the password; tokens in query strings still leak.
- Using the signal context as BaseContext cancels draining requests.
Implementation & operation cost: A config package with a test table and a slightly longer main; both are cheaper than one misconfigured production start.
Configuration is input: parse it, bound it, reject it
Environment variables are untyped strings set by people and deployment templates, so they fail in predictable ways. A duration written as 5 without a unit does not parse. A misspelled name is silently ignored and the default applies. A value can parse correctly and still be dangerous, such as a shutdown budget longer than the platform waits before killing the process, or a trusted-proxy range of 0.0.0.0/0. And a database URL printed at startup leaks its password into logs. The loader answers each one: typed fields, explicit ranges, an error for unknown names under the application prefix, defaults that are safe in production, and a String method that redacts secrets. It also collects every problem before returning, so one failed deploy shows the whole list instead of one error per attempt.
Load, validate and print the effective settings
Load takes the environment as a slice of KEY=value strings, the shape os.Environ returns, rather than calling os.Getenv itself. That keeps it a pure function: tests pass literal slices, and main passes the real environment. Small closures parse each kind of value and append to a shared error list, cross-field rules run at the end, and errors.Join combines everything into one error whose message has one line per problem.
package main
import (
"errors"
"fmt"
"net"
"net/netip"
"net/url"
"slices"
"strconv"
"strings"
"time"
)
type Config struct {
Addr string
Mode string // gin mode: release or debug
Store string // memory or postgres
DatabaseURL *url.URL
ReadHeaderTimeout time.Duration
ShutdownTimeout time.Duration
MaxBodyBytes int64
IdempotencyTTL time.Duration
TrustedProxies []netip.Prefix
}
var known = []string{
"NOTES_ADDR", "NOTES_MODE", "NOTES_STORE", "NOTES_DATABASE_URL", "NOTES_READ_HEADER_TIMEOUT",
"NOTES_SHUTDOWN_TIMEOUT", "NOTES_MAX_BODY_BYTES", "NOTES_IDEMPOTENCY_TTL", "NOTES_TRUSTED_PROXIES",
}
// Load reads KEY=value pairs (os.Environ() in production) and reports every problem at once.
func Load(environ []string) (Config, error) {
env := map[string]string{}
var errs []error
for _, kv := range environ {
k, v, _ := strings.Cut(kv, "=")
if strings.HasPrefix(k, "NOTES_") && !slices.Contains(known, k) {
errs = append(errs, fmt.Errorf("%s: unknown setting", k))
}
env[k] = v
}
str := func(key, def string, allowed ...string) string {
v, ok := env[key]
if !ok {
return def
}
if len(allowed) > 0 && !slices.Contains(allowed, v) {
errs = append(errs, fmt.Errorf("%s: %q is not one of %s", key, v, strings.Join(allowed, ", ")))
}
return v
}
dur := func(key string, def, lo, hi time.Duration) time.Duration {
v, ok := env[key]
if !ok {
return def
}
d, err := time.ParseDuration(v)
switch {
case err != nil:
errs = append(errs, fmt.Errorf("%s: %q is not a duration such as 5s", key, v))
case d < lo || d > hi:
errs = append(errs, fmt.Errorf("%s: %s is outside %s..%s", key, d, lo, hi))
}
return d
}
c := Config{
Addr: str("NOTES_ADDR", ":8080"),
Mode: str("NOTES_MODE", "release", "release", "debug"),
Store: str("NOTES_STORE", "memory", "memory", "postgres"),
ReadHeaderTimeout: dur("NOTES_READ_HEADER_TIMEOUT", 5*time.Second, time.Second, 30*time.Second),
ShutdownTimeout: dur("NOTES_SHUTDOWN_TIMEOUT", 20*time.Second, time.Second, 25*time.Second),
IdempotencyTTL: dur("NOTES_IDEMPOTENCY_TTL", 24*time.Hour, time.Hour, 7*24*time.Hour),
MaxBodyBytes: 1 << 20,
}
if v, ok := env["NOTES_MAX_BODY_BYTES"]; ok {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 1024 || n > 10<<20 {
errs = append(errs, fmt.Errorf("NOTES_MAX_BODY_BYTES: %q must be an integer in 1024..%d", v, 10<<20))
}
c.MaxBodyBytes = n
}
if _, _, err := net.SplitHostPort(c.Addr); err != nil {
errs = append(errs, fmt.Errorf("NOTES_ADDR: %q is not host:port", c.Addr))
}
if v := env["NOTES_TRUSTED_PROXIES"]; v != "" {
for _, s := range strings.Split(v, ",") {
p, err := parseProxy(strings.TrimSpace(s))
switch {
case err != nil:
errs = append(errs, fmt.Errorf("NOTES_TRUSTED_PROXIES: %q is not an IP or CIDR prefix", s))
case p.Bits() == 0:
errs = append(errs, fmt.Errorf("NOTES_TRUSTED_PROXIES: %s would trust every client", p))
default:
c.TrustedProxies = append(c.TrustedProxies, p)
}
}
}
if raw, ok := env["NOTES_DATABASE_URL"]; ok {
u, err := url.Parse(raw)
if err != nil || u.Scheme != "postgres" || u.Host == "" {
errs = append(errs, errors.New("NOTES_DATABASE_URL: must be a postgres:// URL with a host"))
}
c.DatabaseURL = u
}
if c.Store == "postgres" && c.DatabaseURL == nil {
errs = append(errs, errors.New("NOTES_DATABASE_URL: required when NOTES_STORE=postgres"))
}
return c, errors.Join(errs...)
}
func parseProxy(s string) (netip.Prefix, error) {
if p, err := netip.ParsePrefix(s); err == nil {
return p.Masked(), nil
}
a, err := netip.ParseAddr(s)
if err != nil {
return netip.Prefix{}, err
}
return netip.PrefixFrom(a, a.BitLen()), nil
}
// String is what startup logs print: every effective value, secrets redacted.
func (c Config) String() string {
db := "none"
if c.DatabaseURL != nil {
db = c.DatabaseURL.Redacted()
}
return fmt.Sprintf("addr=%s mode=%s store=%s db=%s read_header=%s shutdown=%s max_body=%d idem_ttl=%s proxies=%v",
c.Addr, c.Mode, c.Store, db, c.ReadHeaderTimeout, c.ShutdownTimeout, c.MaxBodyBytes, c.IdempotencyTTL, c.TrustedProxies)
}
func main() {
good := []string{
"HOME=/home/app",
"NOTES_STORE=postgres",
"NOTES_DATABASE_URL=postgres://notes_rw:s3cret@db.internal:5432/notes",
"NOTES_TRUSTED_PROXIES=10.0.0.0/8, 192.0.2.10",
}
if c, err := Load(good); err == nil {
fmt.Println("config ok:", c)
}
if c, err := Load(nil); err == nil {
fmt.Println("defaults:", c)
}
bad := []string{
"NOTES_STORE=postgres",
"NOTES_READ_HEADER_TIMEOUT=5",
"NOTES_SHUTDOWN_TIMEOUT=45s",
"NOTES_SHUTDOWN_TIMOUT=10s",
"NOTES_ADDR=8080",
"NOTES_TRUSTED_PROXIES=0.0.0.0/0",
}
if _, err := Load(bad); err != nil {
fmt.Println("refusing to start:")
for _, line := range strings.Split(err.Error(), "\n") {
fmt.Println(" " + line)
}
}
}The first configuration is valid: the database URL prints with its password replaced by xxxxx, because URL.Redacted masks only the password component, and the single proxy address becomes a /32 prefix. HOME is ignored because only the NOTES_ prefix is checked. With no variables at all the defaults are complete and conservative: release mode, bounded timeouts and no trusted proxies; the memory store default suits development, and a production deploy sets NOTES_STORE=postgres. The bad configuration reports six problems at once: a misspelled name, a duration without a unit, a shutdown budget above the 25-second ceiling, an address without a colon, a proxy range that would trust every client and a missing database URL that the postgres store requires.
The composition root
main does nothing but call run and translate its error into an exit status. run loads configuration, creates the signal context, builds the graph from the inside out, binds the listener, serves, and on a signal drains with a budget. Every constructor from the earlier lessons appears exactly once here, and no other package names a concrete type from another package.
// cmd/api/main.go, package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"example.com/notes-api/internal/config"
"example.com/notes-api/internal/httpapi"
"example.com/notes-api/internal/notes"
"example.com/notes-api/internal/store"
)
func main() {
if err := run(os.Environ()); err != nil {
fmt.Fprintln(os.Stderr, "notes-api:", err)
os.Exit(1)
}
}
func run(environ []string) error {
cfg, err := config.Load(environ)
if err != nil {
return fmt.Errorf("invalid configuration:\n%w", err)
}
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
log.Info("config", "effective", cfg.String())
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Wire from the inside out: store -> service -> handlers -> engine -> server.
st := store.NewMemory() // a Postgres adapter would be opened here and closed after Shutdown
svc, err := notes.NewService(st, time.Now, notes.RandomIDs)
if err != nil {
return err
}
gin.SetMode(cfg.Mode) // before gin.New; GIN_MODE is ignored from here on
engine, err := httpapi.NewRouter(httpapi.NewHandler(svc, log), httpapi.Options{
MaxBodyBytes: cfg.MaxBodyBytes,
IdempotencyTTL: cfg.IdempotencyTTL,
TrustedProxies: cfg.TrustedProxyStrings(),
})
if err != nil {
return err
}
srv := &http.Server{
Handler: engine,
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
IdleTimeout: time.Minute,
// No BaseContext(ctx): a signal must not cancel requests that are draining.
}
ln, err := net.Listen("tcp", cfg.Addr) // a busy port fails here, before "listening" is logged
if err != nil {
return err
}
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(ln) }()
log.Info("listening", "addr", ln.Addr().String())
select {
case err := <-serveErr:
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
log.Info("shutting down", "cause", context.Cause(ctx).Error())
}
stop() // restore default handling: a second Ctrl-C ends the process at once
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
_ = srv.Close() // budget spent: drop what is left rather than hang
return fmt.Errorf("shutdown: %w", err)
}
if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
return err
}
log.Info("stopped")
return nil
}Run this fragment in your own environment; it opens a real socket. Because run returns errors instead of exiting, its deferred calls always execute before os.Exit. gin.SetMode runs before NewRouter calls gin.New, and NewRouter returns the error from SetTrustedProxies, so a bad list stops startup. net.Listen binds before the serving goroutine starts, so a busy port is an immediate error rather than a log line from a goroutine. On SIGTERM the context is cancelled and context.Cause reports "terminated signal received". stop restores default signal handling, Shutdown drains within cfg.ShutdownTimeout using a fresh context, Close drops whatever remains if the budget runs out, and ErrServerClosed from Serve is the normal result.
Startup and shutdown details that bite
Do not pass the signal context to http.Server.BaseContext. Every request context derives from it, so the first SIGTERM would cancel the very requests Shutdown is trying to let finish. Gin reads GIN_MODE once, in its package init, and the fragment then overrides it with SetMode; pick one source of truth, here the validated config, so two settings cannot disagree. The 25-second ceiling on the shutdown budget exists to fit under a platform grace period such as the Kubernetes default of 30 seconds, leaving time for the remaining teardown. Readiness withdrawal, header and idle timeouts, and joining background workers are covered in the server-lifecycle lesson; this root only has to give them one owner and one budget. If a Postgres adapter replaces the memory store, open it before the listener and close it after Shutdown returns, so no request runs against a closed pool.
Test startup like any other code
Load is a pure function of a slice, so a table test covers every rule: each default, each range edge, each unknown name, the redacted String output and the combined error text. The composition root is harder to unit test, which is why it should stay thin. A useful refactor is run(ctx, environ) with the signal context created in main: an integration test can then start the service on 127.0.0.1:0, send one request, cancel the context and assert a clean return within the budget, without sending real signals. Log the effective configuration once at startup; when an incident starts with "which timeout was this pod running with?", that line answers it.
TAKE THIS WITH YOU
Parse configuration into a typed, bounded struct that reports every error at once and redacts secrets, then wire store, service, handlers, engine and server in main, with signal.NotifyContext starting a budgeted Shutdown.
Check your understanding
Why should run not set http.Server.BaseContext to return the signal.NotifyContext context?
Go to the source
Progress stays in this browser. No account needed.