Gin project: a complete REST API · 5 MIN READ

Lay out a Gin service so every import points toward the domain

Organize a Gin API into cmd/api, httpapi, notes and store packages whose imports point toward the domain, with all concrete wiring in main.

One main.go holding handlers, SQL and business rules works until the first test, the second developer or the second storage backend. This unit grows a single notes API over nine lessons, so this first lesson fixes where each piece lives. Later lessons then add CRUD, pagination, problem details, idempotency and versioning without moving code between packages.

gin · A MAP OF THE IDEA

  1. Domain in internal/notes
  2. Adapters import domain
  3. Wire in cmd/api
  4. Check imports in review

Useful when

  • Business rules can be tested and reused without HTTP or a database.
  • A new storage backend or transport is a new adapter plus a line in main.
  • The import graph documents the architecture and can be checked in CI.

Watch out

  • Splitting into many tiny packages early adds ceremony without protection.
  • Package-level globals or os.Getenv calls inside internal packages defeat the layout.

Implementation & operation cost: A few more files and constructor calls than a single main.go; the payoff starts with the first test that needs a fake store.

01

Four packages and one direction of imports

The layout follows the server-project shape from the Go documentation: commands under cmd, everything else under internal. Inside internal the split is by responsibility, not by technical layer. notes is the domain: the Note type, the errors callers can test for, the Service with the business rules and the Store interface the service needs. store holds adapters that satisfy that interface. httpapi turns HTTP requests into service calls and service results into responses. cmd/api/main.go is the composition root that builds and connects them. The rule that keeps this from decaying is the direction of imports: both adapters import notes, notes imports neither, and only main imports everything.

text
notes-api/
  go.mod                    module example.com/notes-api
  cmd/
    api/
      main.go               composition root: config, wiring, http.Server
  internal/
    notes/                  domain: Note, error values, Service, Store interface
      note.go
      errors.go
      service.go
    store/                  adapters that implement notes.Store
      memory.go
      postgres.go
    httpapi/                Gin adapter: handlers, routes, error mapping
      handler.go
      routes.go
      problems.go
      handler_test.go
    config/                 environment parsing and validation

imports:
  cmd/api       -> config, httpapi, notes, store, gin
  httpapi       -> notes, gin
  store         -> notes, a database driver
  notes         -> standard library only
Read the code

The tree is the real module the rest of the unit builds. internal/ is enforced by the go command: only code rooted at notes-api/ may import these packages, so nothing outside the module can couple to them. The imports block is the dependency graph to defend in review. If store ever needs something from httpapi, or notes needs Gin, the arrow points the wrong way and the design, not the compiler, is the thing to fix.

02

The whole service in one runnable file

The runnable model keeps the same boundaries but folds the four packages into one file, with a comment where each package would begin. Read the types as if they were in separate directories: Note, the errors, Store and Service belong to notes; MemoryStore belongs to store; NoteService, Handler, NewRouter and writeError belong to httpapi; main is cmd/api. The program wires the pieces once and sends four requests through the engine with ServeHTTP.

go
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"

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

// ---- internal/notes: the domain. Imports only the standard library. ----

type Note struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}

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

// Store is what the service needs from persistence; adapters implement it.
type Store interface {
	Insert(ctx context.Context, n Note) error
	Get(ctx context.Context, id string) (Note, error)
}

type Service struct {
	store  Store
	nextID func() string
}

func NewService(store Store, nextID func() string) *Service {
	return &Service{store: store, nextID: nextID}
}

func (s *Service) Create(ctx context.Context, title string) (Note, error) {
	title = strings.TrimSpace(title)
	if title == "" || len(title) > 80 {
		return Note{}, ErrInvalid
	}
	n := Note{ID: s.nextID(), Title: title}
	return n, s.store.Insert(ctx, n)
}

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

// ---- internal/store: an adapter. Imports notes, never httpapi. ----

type MemoryStore struct {
	mu    sync.RWMutex
	notes map[string]Note
}

func NewMemoryStore() *MemoryStore {
	return &MemoryStore{notes: map[string]Note{}}
}

func (m *MemoryStore) Insert(_ context.Context, n Note) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.notes[n.ID] = n
	return nil
}

func (m *MemoryStore) Get(_ context.Context, id string) (Note, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	n, ok := m.notes[id]
	if !ok {
		return Note{}, ErrNotFound
	}
	return n, nil
}

// ---- internal/httpapi: the Gin adapter. Imports notes, never store. ----

type NoteService interface {
	Create(ctx context.Context, title string) (Note, error)
	Get(ctx context.Context, id string) (Note, error)
}

type Handler struct{ svc NoteService }

func NewRouter(h *Handler) *gin.Engine {
	r := gin.New()
	r.Use(gin.Recovery())
	r.POST("/notes", h.create)
	r.GET("/notes/:id", h.get)
	return r
}

func (h *Handler) create(c *gin.Context) {
	var in struct {
		Title string `json:"title"`
	}
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "malformed body"})
		return
	}
	n, err := h.svc.Create(c.Request.Context(), in.Title)
	if err != nil {
		writeError(c, err)
		return
	}
	c.JSON(http.StatusCreated, n)
}

func (h *Handler) get(c *gin.Context) {
	n, err := h.svc.Get(c.Request.Context(), c.Param("id"))
	if err != nil {
		writeError(c, err)
		return
	}
	c.JSON(http.StatusOK, n)
}

func writeError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrNotFound):
		c.JSON(http.StatusNotFound, gin.H{"error": "note not found"})
	case errors.Is(err, ErrInvalid):
		c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "title must be 1-80 characters"})
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
	}
}

// ---- cmd/api: the composition root. The only place that knows every concrete type. ----

func main() {
	gin.SetMode(gin.TestMode)

	seq := 0
	nextID := func() string { seq++; return fmt.Sprintf("n%d", seq) }

	store := NewMemoryStore()
	svc := NewService(store, nextID)
	router := NewRouter(&Handler{svc: svc})

	requests := []struct{ method, path, body string }{
		{http.MethodPost, "/notes", `{"title":"  Buy milk "}`},
		{http.MethodGet, "/notes/n1", ""},
		{http.MethodPost, "/notes", `{"title":"   "}`},
		{http.MethodGet, "/notes/n9", ""},
	}
	for _, rq := range requests {
		w := httptest.NewRecorder()
		req := httptest.NewRequest(rq.method, rq.path, strings.NewReader(rq.body))
		req.Header.Set("Content-Type", "application/json")
		router.ServeHTTP(w, req)
		fmt.Println(rq.method, rq.path, w.Code, w.Body.String())
	}
}
Read the code

The domain trims the title and rejects an empty or overlong one with ErrInvalid; that rule lives in Service, so a CLI or a queue consumer would get it too. MemoryStore satisfies Store without naming it, and it returns ErrNotFound from the domain package rather than inventing its own error. The Handler depends on NoteService, an interface listing the two calls it makes, so httpapi never sees MemoryStore. main is the only function that names every concrete type: it builds the ID source, the store, the service and the router, in that order. The output shows a created note, a read, a 422 for a blank title and a 404, all mapped in writeError, which the problem-details lesson later moves into one middleware.

03

What belongs in main, and what never does

The composition root reads configuration, constructs concrete adapters, connects them through constructors and owns the process lifecycle: starting the server, handling signals and calling os.Exit. It should read like a wiring diagram, a few dozen lines with no business decisions. Everything else moves out. Packages under internal should not call os.Getenv, parse flags, open connections in init, keep package-level singletons or call log.Fatal. Each of those hides an input or an exit path from the caller and makes the package impossible to test in isolation. When a package needs a setting, it takes it as a constructor argument or a field; when it fails, it returns an error and lets main decide whether that ends the process. The config-and-startup lesson at the end of this unit fills in main completely.

04

Layouts that look tidy and still couple everything

Package-by-layer trees such as models, controllers and services look organized, but every package imports models, everything is exported to cross the boundaries, and a change to one feature touches all of them. A utils or common package becomes the place where unrelated code goes to import each other. A domain function that accepts *gin.Context or returns gin.H has quietly made Gin part of the business rules, so a background job now needs a fake HTTP request. An httpapi handler that imports store directly to save a layer bypasses the service and its rules. A top-level pkg directory in a service that no other module imports adds a path segment and no protection; internal already says what it means. Start with few packages named for what they provide, and split one only when it has a second reason to change.

05

Check the direction of imports in review

Go refuses to compile an import cycle, so the most damaging mistakes surface early, but a one-way dependency in the wrong direction compiles fine. Make the intended graph visible and cheap to check. go list prints each package with its imports, and a short pipeline can fail a CI job when the domain starts depending on Gin or on an adapter. Review a new import in notes with the same care as a new dependency in go.mod.

bash
# Each package in the module and what it imports.
go list -f '{{.ImportPath}} -> {{join .Imports " "}}' ./...

# The domain must not depend on Gin, a store or the HTTP adapter.
go list -deps ./internal/notes \
  | grep -E 'gin-gonic|notes-api/internal/(store|httpapi)' \
  && echo "layering violation" || echo "notes is clean"
Read the code

Run these commands in your own checkout of the module. The first prints one line per package, for example "example.com/notes-api/internal/store -> context example.com/notes-api/internal/notes sync", which is exactly the arrow the layout promises. The second lists every transitive dependency of internal/notes and searches it for Gin or the two adapter packages; any match prints "layering violation", and a CI step can turn that into a failing exit code.

TAKE THIS WITH YOU

Keep internal/notes free of Gin and storage imports, let the HTTP and storage adapters import the domain, and confine concrete wiring, configuration and os.Exit to cmd/api/main.go.

Check your understanding

In the notes API layout, which package is allowed to import the store, the HTTP adapter and the domain together?

Go to the source

Progress stays in this browser. No account needed.