The database is designed, so the next step is the Go backend. I know some Go, but I've never built a project "the Go way", following the conventions that experienced Go developers use. So before writing a single line of code, I wanted every big decision made: how the code is organised, how a request travels through it, and exactly what the API looks like.

This post is that plan. The next one is the actual building.

A quick note on effort, because I asked myself before starting: for someone still learning Go, the basic backend (login checks plus adding, editing and listing everything) looks like roughly 40 to 70 hours of work. Barcode lookup and the first deployment add a bit on top. We'll see how close that guess ends up.

Go has no official layout

Coming from frameworks that tell you where everything goes, this surprised me. Go doesn't have an official project structure. The Go team's own advice mostly comes down to "start simple and grow it when you need to". There's a popular GitHub repository with a big recommended layout that looks official, but it isn't, and plenty of Go developers think it's too much for small projects.

Two conventions are used almost everywhere, though, and I'm following both:

  • cmd/ holds the programs you can run. Mine has one, cmd/api/main.go, which starts the server. Its job is short: read the settings, connect to the database, plug everything together and start listening. Later the daily reminder job could become a second program next to it.
  • internal/ holds all the rest of the code. Go has a special rule for this folder name: code inside it can't be imported by other projects. For an app, that's simply the right default.

Both folders sit side by side at the top of the repository, next to the migrations folder from the last post.

Grouping by feature

There are two common ways to organise the code inside internal/. One groups by layer: a folder for all the request handlers, one for all the business logic, one for all the database code. The other groups by feature: a folder for products, a folder for pantry items, and each one holds everything about that feature.

I always prefer grouping by feature, and it turns out that's also what Go developers recommend. Changing products means working in one folder instead of jumping between four. It also reads better in Go, where you refer to code through its folder name: product.Service instead of services.ProductService.

Here's the full structure I ended up with:

pantry-api/ ├── cmd/api/main.go starts everything ├── internal/ │ ├── product/ product.go, handler.go, service.go, store.go │ ├── pantry/ item.go, handler.go, service.go, store.go │ ├── category/ handler.go, store.go │ ├── auth/ checks the login token │ ├── server/ builds the router, lists all routes │ ├── database/ opens the database connection │ ├── config/ reads settings │ └── httpjson/ writes JSON responses and errors ├── migrations/ └── go.mod 

The feature folders (product, pantry, category) each own their code. The other folders are small shared tools that the features use. Categories have no business rules, just a fixed list, so they skip the middle layer.

One habit of mine needed adjusting. I usually move shared code up into the closest parent folder. In Go, every folder is its own package, and if a parent imports its children while a child imports the parent, Go refuses to compile. That's called an import cycle. So shared code gets its own small folder instead, named for what it does, like httpjson. Names like utils, common or shared are considered a bad sign in Go, because they say nothing about what's inside and slowly turn into junk drawers.

Three layers, one job each

Inside each feature folder, the code is split into three layers, and a request travels down through them in order:

how a request travels · auth, then three layers per feature

  • The handler deals with the web side: reading the request, checking it has the right shape, writing the response. It knows nothing about SQL.
  • The service holds the business rules, like "throwing something away records 100% wasted unless told otherwise" or "adding five yogurts creates five rows". It knows nothing about HTTP.
  • The store talks to the database and does nothing else.

Small Go apps sometimes skip the middle layer and let handlers talk to the database directly. My app has real rules, so it gets all three. Splitting things this way also means each layer can be tested on its own, which matters later.

Passing data between the layers

My next question was whether I need a separate "models" folder for the data types that travel between layers. The answer was no, because a models folder is grouping by layer again. Instead there are two kinds of types, each living where it's used.

One core type per feature. For example Product lives in product.go inside the product folder. The business logic and the database code both use it, and database rows are read straight into it.

type Product struct { ID uuid.UUID OwnerID uuid.UUID Name string CategoryID string Barcode *string // a pointer means it can be empty CreatedAt time.Time UpdatedAt time.Time } 

Request and response types in the handler. What the API accepts is not the same thing as a product. An app must never be able to set the owner or the creation time; the owner always comes from the login token. So the handler has its own small types for what goes in and comes out, and converts between those and Product. It's a bit of extra code, but it stops the shape of the API and the shape of the database from leaking into each other.

I skipped a third kind, a separate type for "a database row". Some projects have one, but here it would just mean copying every field twice more for nothing.

product.go also holds the feature's named errors, like ErrNotFound. When the database code can't find a product, it returns ErrNotFound, and the handler turns that into a "404 Not Found" response without knowing anything about the database. In Go these are called sentinel errors, and they're how the layers report problems to each other cleanly.

Built to be tested

I wanted the code easy to test from day one, not bolted on later. In Go that comes down to a few habits:

  • No global variables for the database or settings. Each piece of code gets what it needs handed to it when it's created, like product.NewService(store). A test can hand it something else.
  • Small interfaces, defined by the code that uses them. Go's saying is "accept interfaces, return structs". If the product logic needs to save products, the product logic itself describes the two or three methods it needs. The real database code fits that description automatically, and so does a fake one in a test. Go doesn't even need an "implements" keyword for this.
  • Each layer is tested in its own way. Handlers are tested with Go's built-in httptest package, which sends a fake request and checks the response, no running server needed. Business logic is tested with a fake store, so the rules are checked without a database. Database code is tested against a real Postgres database, because faking SQL only proves you called it the way you expected.

All routes in one file

I'm used to a router pattern where all the routes are registered in one place. In Go that's a common and well-liked approach too, with one difference: it shouldn't be a single global object that everything registers into. Instead, a function builds a fresh router each time it's called. That way tests can create a clean server whenever they need one.

So internal/server/routes.go lists every route, and reads like a table of contents for the whole API:

mux.HandleFunc("GET /healthz", healthz) mux.Handle("GET /v1/products", requireAuth(http.HandlerFunc(products.List))) mux.Handle("POST /v1/products", requireAuth(http.HandlerFunc(products.Create))) mux.Handle("GET /v1/products/{id}", requireAuth(http.HandlerFunc(products.Get))) 

The handlers themselves still live in their feature folders; this file only points to them. And I don't need a router library: since Go 1.22, the standard library understands methods and path parameters like {id} on its own.

One thing to avoid is Go's built-in global router, http.DefaultServeMux. Any code in the program, including libraries, can add routes to it without you noticing.

Smaller decisions

Hosting on Vercel. I checked first whether that would clash with the structure. It doesn't: Vercel runs a normal Go server and even looks for cmd/api/main.go on its own. The server just has to listen on the port Vercel gives it through a PORT setting.

Settings from a .env file. I'm used to .env files, so locally a small library called godotenv loads one when the server starts. On Vercel there's no such file, because it's never committed to Git; the same settings are entered in Vercel's dashboard instead. The code tries to load the file and simply carries on if it isn't there, so it works the same in both places.

Logging, simple for now. Go has structured logging built in (log/slog), so no library is needed. For now I'm sticking to three habits: use slog everywhere instead of print statements, log in key-value form, and log each error once, where it's finally handled, not at every layer it passes through. The fancier parts, like tagging every log line with the request and the user, are saved for the end. I usually like doing everything properly right away, but learning that alongside the API itself felt like too much at once.

One shape for all errors. Every error response looks the same, so the apps can handle errors in one place:

{ "error": { "code": "not_found", "message": "Product not found" } } 

I normally keep it flat, without the outer error, but nesting it keeps error responses clearly apart from normal ones and leaves room for extra details later, like which form field was wrong. The code is for the apps to check; the message is for people.

CORS later. The settings that let the web app call the API from another address only matter once the Vue app exists, so they wait until then.

The API, before the code

The last part of the plan is the API contract: a list of every endpoint, what it accepts and what it returns. Writing it first gives the backend a clear target, and means the web and mobile apps won't hit surprises later. The full version will live in the repository as docs/api.md; here are the decisions behind it.

The general rules:

  • Every address starts with /v1 (more on that below).
  • Everything is JSON, with field names like expiryDate, since both apps are JavaScript.
  • Dates look like "2026-11-20".
  • Every request except the health check must carry the Supabase login token.
  • If you ask for something that belongs to someone else, the answer is "not found", not "forbidden". That way the API never even admits it exists.
  • Every list comes wrapped in an object, {"items": [...]}, rather than as a bare list. I'll explain why in the pantry items part.

Products get full create, read, update and delete, even if the app ends up not using all of it. My first idea was the opposite: products only readable, created automatically when you add a pantry item. But users need to rename products, which was the whole reason products are per user in the database design. In the end I kept both: full CRUD, plus a shortcut.

The shortcut: adding items can create the product too. When you add yogurts for a brand-new product, the request can carry either the id of an existing product or the details of a new one. The backend saves the product and the items together in one database transaction, which means either everything is saved or nothing is. A failure halfway can never leave a product with no items.

Two small rules come with it. Deleting a product that pantry items still use is refused. And if the new product's barcode already exists for this user, the request is refused rather than quietly reusing the old product, which would ignore the name the user just typed.

Pantry items follow the same pattern, plus two extra actions. Here's every route at once:

Route What it does
GET /v1/pantry-items List items (only what's in the pantry, unless filtered)
GET /v1/pantry-items/{id} One item
POST /v1/pantry-items Add one or more items
PUT /v1/pantry-items/{id} Edit the expiry date or note
DELETE /v1/pantry-items/{id} Remove an item entered by mistake
POST /v1/pantry-items/{id}/use Mark it as used
POST /v1/pantry-items/{id}/discard Mark it as thrown away, with how much was wasted

The interesting part was the difference between deleting and throwing away. From the app's point of view, throwing something away feels like removing it, so delete seemed like a natural fit. But delete removes the row, and a thrown-away yogurt has to stay in the database, or it never shows up in the waste stats. So delete only means "I entered this by mistake", and throwing away is a change of status.

For that status change I had two options: send the new status through the normal edit (PUT), or give each change its own action. I went with separate actions. Each one has its own small set of rules: throwing away needs an amount (100% unless the user says otherwise), and both record when it happened. Keeping them separate means the normal edit can never change the status at all, so there's exactly one way to do it. Both actions only work on items still in the pantry.

History is a filter, not a separate page. Used and thrown-away items come from the same list route with a filter: ?status=used,discarded. Without a filter you get what's in the pantry, sorted by expiry date. With the history filter, items are sorted by when they were used or thrown away, newest first.

Paging is left for later, on purpose. History grows forever, so eventually it needs to come in pages. The plan is already written down, but adding it now felt like one complication too many. This is where the {"items": [...]} wrapper earns its place: when paging arrives, a "next page" field can sit right next to items, and the existing apps keep working. If lists were bare arrays, there'd be nowhere to put it without breaking them.

The barcode lookup is one route, GET /v1/barcodes/{barcode}, and it handles the whole scan in a single answer:

  • If the user already has a product with that barcode, it comes back straight away, and the app jumps to "how many, and when do they expire?".
  • If not, but Open Food Facts knows the barcode, the answer carries a suggestion (name, brand, size, picture) to pre-fill the new product form.
  • If nobody knows it, both are empty and the app shows a blank form.

The edge case worth thinking about was Open Food Facts being down. Returning an error would block the user over something that's only a convenience. So the backend answers as if the barcode simply wasn't found, letting the user type the name by hand, and doesn't remember that miss, so the next scan tries again.

Two small ones: GET /v1/me returns the logged-in user's id and email, read straight from the login token. It's mainly the first check that logging in works end to end. And GET /healthz answers "is everything working right now?" by checking the server and running a tiny database query. Hosting platforms and uptime monitors call it every minute or so, and it'll be the very first endpoint I build.

What the /v1 is for

Every route starts with /v1 so that if I ever need to change the API in a way that would break the apps, the new version can live at /v2 while older apps keep using /v1.

In the code, the version only exists in routes.go, as part of each address. The handlers, the business logic and the database code don't know versions exist, and there are no v1 folders. If a breaking change ever comes, only the changed routes get a new handler under /v2, and both versions share everything underneath.

My first reaction was: won't that get messy over time? It can, but only if old versions are never cleaned up. Most changes don't need a new version at all: adding a field or a new route doesn't break anything, because apps just ignore what they don't know. Only renaming or removing things does. When a second version does appear, the old one gets deleted once the apps have moved over. Since I control both apps, that's quick; the phone app is the only one that lags, because people don't always update. Most likely this project stays on /v1 forever, and the prefix just keeps the door open for free.

What's next

Every big decision is now made, and none of it is code yet. That felt slow at times, but it means the coding can focus on learning Go rather than on rethinking the design halfway through.

A few things are deliberately parked for an end-of-project round of updates: paging for history, the fuller logging setup, CORS, shutting the server down cleanly, and a database for tests.

Next post: the actual implementation. Setting up the repository, running the migrations against Supabase, and getting /healthz to answer. That first answer will prove the settings, database, router and server all work together. Then the real endpoints.

For more, you can follow me on LinkedIn, GitHub, or Instagram.