Gin project: a complete REST API · 5 MIN READ

Give Gin handlers their dependencies through a struct, not globals or context keys

Write handlers as methods on a struct built by a constructor, depend on small consumer-defined interfaces and swap in a fake store for tests.

A handler that reaches for a package-level database variable works on the first day and fights you afterwards: tests share state, parallel tests race, and no signature tells a reviewer what the handler can touch. Passing dependencies through a constructor makes them visible, replaceable and checked by the compiler. This lesson does that for the notes API, including the clock and the ID source.

gin · A MAP OF THE IDEA

  1. List what handlers call
  2. Declare consumer interface
  3. Inject via constructor
  4. Swap fakes in tests

Useful when

  • Every collaborator is visible in one struct and one constructor call.
  • Tests run the real router with a fake store, clock and IDs.
  • Missing wiring fails at startup or at compile time, not on a request.

Watch out

  • A typed nil pointer inside an interface passes a nil check.
  • Hand-written fakes need a mutex if tests share them across goroutines.

Implementation & operation cost: Constructor parameters and a few small interfaces; main grows by a handful of lines per dependency.

01

What globals and context lookups cost

Both shapes below compile and serve requests. The first keeps the store in a package variable, so every test in the package shares one instance, a test that forgets to reset it leaks data into the next, and t.Parallel turns that into a race. The second hides the dependency in the Gin context: some middleware must call c.Set first, the type assertion moves a compile-time fact to run time, and a forgotten Use call becomes a panic on the first request rather than a build error. time.Now and an unseeded random ID generator are hidden globals of the same kind; they are why a response body cannot be compared byte for byte in a test.

go
// Hidden dependencies: nothing in the signature says what getNote touches.
var db *store.Memory // set in init or main; shared by every test

func getNote(c *gin.Context) {
	n, err := db.Get(c.Request.Context(), c.Param("id"))
	// ...
}

// A service locator through the context: the dependency is resolved at
// runtime, and a missing middleware becomes a panic on the first request.
func getNoteFromContext(c *gin.Context) {
	svc := c.MustGet("notes").(*notes.Service)
	// ...
}
Read the code

This fragment shows what to avoid and is not meant to compile on its own. getNote has no parameters that mention storage, so a reader must search the package to learn where db is assigned. getNoteFromContext depends on a string key and a concrete type assertion; renaming the key or changing the type is not caught until a request hits the route. Request-scoped values such as the authenticated user do belong in the context; long-lived dependencies do not.

02

Handlers as methods, dependencies as fields

The notes service now takes three dependencies in its constructor: a Store, a clock and an ID source. The HTTP Handler takes a NoteService and a *slog.Logger. Register attaches method values such as h.getNote to any gin.IRouter, so the same handler works on an engine or a route group. The test half of the file builds the same graph with a fake store, a fixed clock and sequential IDs, then runs a healthy and a failing scenario through the real router.

go
package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// ---- internal/notes ----

type Note struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	CreatedAt time.Time `json:"createdAt"`
}

var ErrNotFound = errors.New("notes: not found")

type Store interface {
	Insert(ctx context.Context, n Note) error
	Get(ctx context.Context, id string) (Note, error)
}

type Service struct {
	store  Store
	now    func() time.Time
	nextID func() string
}

func NewService(store Store, now func() time.Time, nextID func() string) (*Service, error) {
	if store == nil || now == nil || nextID == nil {
		return nil, errors.New("notes: NewService needs a store, a clock and an ID source")
	}
	return &Service{store: store, now: now, nextID: nextID}, nil
}

func (s *Service) Create(ctx context.Context, title string) (Note, error) {
	n := Note{ID: s.nextID(), Title: strings.TrimSpace(title), CreatedAt: s.now().UTC()}
	if err := s.store.Insert(ctx, n); err != nil {
		return Note{}, fmt.Errorf("insert note: %w", err)
	}
	return n, nil
}

func (s *Service) Get(ctx context.Context, id string) (Note, error) {
	return s.store.Get(ctx, id)
}

// ---- internal/httpapi ----

// NoteService lists only what these handlers call. *notes.Service satisfies it implicitly.
type NoteService interface {
	Create(ctx context.Context, title string) (Note, error)
	Get(ctx context.Context, id string) (Note, error)
}

type Handler struct {
	notes NoteService
	log   *slog.Logger
}

func NewHandler(notes NoteService, log *slog.Logger) *Handler {
	return &Handler{notes: notes, log: log}
}

func (h *Handler) Register(r gin.IRouter) {
	r.GET("/notes/:id", h.getNote)
	r.POST("/notes", h.createNote)
}

func (h *Handler) getNote(c *gin.Context) {
	id := c.Param("id")
	n, err := h.notes.Get(c.Request.Context(), id)
	switch {
	case errors.Is(err, ErrNotFound):
		c.JSON(http.StatusNotFound, gin.H{"error": "note not found"})
	case err != nil:
		h.log.Error("get note", "id", id, "err", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
	default:
		c.JSON(http.StatusOK, n)
	}
}

func (h *Handler) createNote(c *gin.Context) {
	var in struct {
		Title string `json:"title" binding:"required"`
	}
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})
		return
	}
	n, err := h.notes.Create(c.Request.Context(), in.Title)
	if err != nil {
		h.log.Error("create note", "err", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
		return
	}
	c.JSON(http.StatusCreated, n)
}

// ---- handler_test.go: a fake Store the test fully controls ----

type fakeStore struct {
	notes map[string]Note
	err   error // when set, every call fails with it
	calls []string
}

func (f *fakeStore) Insert(_ context.Context, n Note) error {
	f.calls = append(f.calls, "Insert "+n.ID)
	if f.err != nil {
		return f.err
	}
	f.notes[n.ID] = n
	return nil
}

func (f *fakeStore) Get(_ context.Context, id string) (Note, error) {
	f.calls = append(f.calls, "Get "+id)
	if f.err != nil {
		return Note{}, f.err
	}
	n, ok := f.notes[id]
	if !ok {
		return Note{}, ErrNotFound
	}
	return n, nil
}

func newTestRouter(store Store, log *slog.Logger) (*gin.Engine, error) {
	clock := func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }
	seq := 0
	ids := func() string { seq++; return fmt.Sprintf("n%d", seq) }
	svc, err := NewService(store, clock, ids)
	if err != nil {
		return nil, err
	}
	r := gin.New()
	NewHandler(svc, log).Register(r)
	return r, nil
}

func send(r http.Handler, method, path, body string) {
	w := httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
	fmt.Println(method, path, w.Code, w.Body.String())
}

func main() {
	gin.SetMode(gin.TestMode)
	log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{} // drop the timestamp so output is stable
			}
			return a
		},
	}))

	if _, err := NewService(nil, time.Now, nil); err != nil {
		fmt.Println("wiring error:", err)
	}

	healthy := &fakeStore{notes: map[string]Note{
		"n7": {ID: "n7", Title: "Write tests", CreatedAt: time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)},
	}}
	r, err := newTestRouter(healthy, log)
	if err != nil {
		panic(err)
	}
	send(r, http.MethodGet, "/notes/n7", "")
	send(r, http.MethodPost, "/notes", `{"title":"Review PR"}`)
	fmt.Println("store calls:", healthy.calls)

	broken := &fakeStore{err: errors.New("dial tcp 192.0.2.10:5432: connection refused")}
	r, err = newTestRouter(broken, log)
	if err != nil {
		panic(err)
	}
	send(r, http.MethodGet, "/notes/n7", "")
}
Read the code

NewService refuses a nil dependency, so the first output line is a wiring error at startup instead of a nil-pointer panic during a request. With the healthy fake, GET returns the seeded note and POST creates n1 with the fixed timestamp 2026-01-02T03:04:05Z, which is why the body is stable enough to compare. The fake records every call, so the test can assert that the handler asked for n7 and inserted n1 without inspecting private state. The broken fake returns a dial error: the handler logs the cause through its injected logger (the time attribute is dropped to keep output stable) and the client receives only a generic 500 body.

03

Declare the interface where it is consumed

httpapi declares NoteService with exactly the two methods its handlers call, and notes declares Store with exactly what the service calls. The concrete types never mention these interfaces; Go satisfies them implicitly, which is what lets the consumer own the definition. That keeps interfaces small, so a fake is a dozen lines, and it keeps the import arrow pointing from adapter to domain. A provider-side interface with twenty methods that mirrors the store invites fakes that panic on the eighteen methods nobody meant to call. Constructors accept interfaces and return concrete types: NewService returns *Service, and each caller decides which slice of it to depend on. A one-line assertion keeps the provider and the consumer from drifting apart silently.

go
// internal/httpapi/handler.go: the consumer declares what it calls.
type NoteService interface {
	Create(ctx context.Context, title string) (notes.Note, error)
	Get(ctx context.Context, id string) (notes.Note, error)
}

// cmd/api/main.go or a test: break the build if the provider drifts.
var _ httpapi.NoteService = (*notes.Service)(nil)
Read the code

This fragment belongs in the module from the layout lesson and compiles there, not on its own. The blank-identifier assignment converts a typed nil *notes.Service to httpapi.NoteService at compile time; if someone renames Get or changes its signature, the build fails at this line with a message naming the missing method, instead of failing later where the router is wired. Exporting the interface is what makes this assertion possible from main.

04

Constructors validate wiring; fakes control the world

A constructor is the right place to reject an incomplete graph, because it runs once at startup where a clear error is cheap. One Go subtlety limits that check: a nil *MemoryStore stored in a Store interface is not equal to nil, so the guard only catches dependencies that were never assigned. For tests, prefer a small hand-written fake over a mocking framework: a map for state, an err field to inject failure and a calls slice to observe what happened. Assert outcomes such as the status, the body and the effect on the fake, not the exact order of every internal call, or the test breaks on every refactor. Build a new fake and a new router per test case; this fake has no mutex, which is fine only because nothing shares it. The API-tests lesson turns this into a full table.

05

Review questions for a new handler

When a pull request adds a handler, three questions catch most dependency problems. Can the handler be constructed in a test without a network, a file or an environment variable? Does its struct list every collaborator it uses, including time and randomness? Is each interface field declared in the consuming package with only the methods it calls? If any answer is no, the missing piece is usually a constructor argument. The cost is a few more lines in main; the benefit is that every test from here on builds the real router with controlled edges.

TAKE THIS WITH YOU

Build handlers from a struct whose fields are small interfaces declared by the consumer, inject the clock and ID source too, and let tests pass a fake store through the same constructor production uses.

Check your understanding

In the notes API, which package should declare the NoteService interface that the HTTP handlers depend on?

Go to the source

Progress stays in this browser. No account needed.