The Go backend
The backend is one Go module with three packages: internal/notes for the store and the handlers, cmd/server for the process, and web for the embedded frontend. It has no framework: the router is the standard library since Go 1.22, and the database layer is database/sql with a pure-Go SQLite driver, so the build needs no cgo.
The API
| Method and path | Body | Answer |
|---|---|---|
| GET /api/notes | none | 200 with a JSON array, newest first |
| POST /api/notes | {"title": "...", "body": "..."} | 201 with the created note, 400 or 422 on bad input |
| GET /api/notes/{id} | none | 200 with the note, 404 when it does not exist |
| DELETE /api/notes/{id} | none | 204, or 404 when it does not exist |
An error is always the same object, {"error": "..."}, so the frontend has one branch for every failure. The status code carries the meaning and the message is for a person reading a log.
The store
The interface is four methods, and the SQLite implementation is the only one the server uses. It opens the database, creates the table if it is missing, and returns ErrNotFound for a missing row instead of sql.ErrNoRows, so the handler does not import the database package.
package notes
import (
"context"
"database/sql"
"errors"
"fmt"
_ "modernc.org/sqlite"
)
// ErrNotFound is returned when a note does not exist.
var ErrNotFound = errors.New("note not found")
// Note is one record of the service.
type Note struct {
ID int64 `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
// Store keeps notes.
type Store interface {
List(ctx context.Context) ([]Note, error)
Create(ctx context.Context, n Note) (Note, error)
Get(ctx context.Context, id int64) (Note, error)
Delete(ctx context.Context, id int64) error
}
// SQLite is a Store backed by one database file.
type SQLite struct {
db *sql.DB
}
// OpenSQLite opens the database and creates the schema.
func OpenSQLite(path string) (*SQLite, error) {
db, err := sql.Open("sqlite", path)
if err != nil {
return nil, err
}
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
body TEXT NOT NULL
)`)
if err != nil {
db.Close()
return nil, fmt.Errorf("create schema: %w", err)
}
return &SQLite{db: db}, nil
}
// Close closes the database.
func (s *SQLite) Close() error { return s.db.Close() }
// List returns every note, newest first.
func (s *SQLite) List(ctx context.Context) ([]Note, error) {
rows, err := s.db.QueryContext(ctx, `SELECT id, title, body FROM notes ORDER BY id DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Note
for rows.Next() {
var n Note
if err := rows.Scan(&n.ID, &n.Title, &n.Body); err != nil {
return nil, err
}
out = append(out, n)
}
return out, rows.Err()
}
// Create inserts a note and returns it with its id.
func (s *SQLite) Create(ctx context.Context, n Note) (Note, error) {
res, err := s.db.ExecContext(ctx, `INSERT INTO notes (title, body) VALUES (?, ?)`, n.Title, n.Body)
if err != nil {
return Note{}, err
}
id, err := res.LastInsertId()
if err != nil {
return Note{}, err
}
n.ID = id
return n, nil
}
// Get returns one note.
func (s *SQLite) Get(ctx context.Context, id int64) (Note, error) {
var n Note
err := s.db.QueryRowContext(ctx, `SELECT id, title, body FROM notes WHERE id = ?`, id).
Scan(&n.ID, &n.Title, &n.Body)
if errors.Is(err, sql.ErrNoRows) {
return Note{}, ErrNotFound
}
return n, err
}
// Delete removes one note.
func (s *SQLite) Delete(ctx context.Context, id int64) error {
res, err := s.db.ExecContext(ctx, `DELETE FROM notes WHERE id = ?`, id)
if err != nil {
return err
}
affected, err := res.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return ErrNotFound
}
return nil
}
The driver is modernc.org/sqlite, a translation of the C library to Go rather than a wrapper around it. That choice keeps CGO_ENABLED=0 and a static binary, which is what makes the single-file deployment on the next page possible.
The tests use a second implementation in memory_test.go: a slice and a counter behind the same interface, which makes it a drop-in replacement. That is the fake-versus-mock argument of the testing group applied to a real service: the fake is fifty lines, it lives next to the test, and the handler code cannot tell it from SQLite.
package notes
import "context"
// Memory is a Store that keeps notes in a slice. Tests use it.
type Memory struct {
next int64
notes []Note
}
// NewMemory returns an empty Memory store.
func NewMemory() *Memory { return &Memory{} }
// List returns every note, newest first.
func (m *Memory) List(context.Context) ([]Note, error) {
out := make([]Note, len(m.notes))
for i, n := range m.notes {
out[len(m.notes)-1-i] = n
}
return out, nil
}
// Create appends a note.
func (m *Memory) Create(_ context.Context, n Note) (Note, error) {
m.next++
n.ID = m.next
m.notes = append(m.notes, n)
return n, nil
}
// Get returns one note.
func (m *Memory) Get(_ context.Context, id int64) (Note, error) {
for _, n := range m.notes {
if n.ID == id {
return n, nil
}
}
return Note{}, ErrNotFound
}
// Delete removes one note.
func (m *Memory) Delete(_ context.Context, id int64) error {
for i, n := range m.notes {
if n.ID == id {
m.notes = append(m.notes[:i], m.notes[i+1:]...)
return nil
}
}
return ErrNotFound
}
The handlers
Each route is a pattern with a method and a path parameter, which Go 1.22 added to ServeMux. MaxBytesReader stops a large body, DisallowUnknownFields turns a typo in a JSON field into a 400 instead of a silently ignored value, and PathValue returns the id without a regular expression.
package notes
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
)
// Handler returns the API routes of the notes service.
func Handler(store Store, log *slog.Logger) http.Handler {
h := &handlers{store: store, log: log}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/notes", h.list)
mux.HandleFunc("POST /api/notes", h.create)
mux.HandleFunc("GET /api/notes/{id}", h.get)
mux.HandleFunc("DELETE /api/notes/{id}", h.delete)
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "no such endpoint")
})
return mux
}
type handlers struct {
store Store
log *slog.Logger
}
func (h *handlers) list(w http.ResponseWriter, r *http.Request) {
items, err := h.store.List(r.Context())
if err != nil {
h.fail(w, err)
return
}
if items == nil {
items = []Note{}
}
writeJSON(w, http.StatusOK, items)
}
func (h *handlers) create(w http.ResponseWriter, r *http.Request) {
var input struct {
Title string `json:"title"`
Body string `json:"body"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
if input.Title == "" {
writeError(w, http.StatusUnprocessableEntity, "title is required")
return
}
note, err := h.store.Create(r.Context(), Note{Title: input.Title, Body: input.Body})
if err != nil {
h.fail(w, err)
return
}
h.log.Info("note created", "id", note.ID)
writeJSON(w, http.StatusCreated, note)
}
func (h *handlers) get(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
note, err := h.store.Get(r.Context(), id)
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusOK, note)
}
func (h *handlers) delete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
if err := h.store.Delete(r.Context(), id); err != nil {
h.fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *handlers) fail(w http.ResponseWriter, err error) {
if errors.Is(err, ErrNotFound) {
writeError(w, http.StatusNotFound, "note not found")
return
}
h.log.Error("request failed", "err", err)
writeError(w, http.StatusInternalServerError, "internal error")
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
// CORS allows the Vite dev server to call the API from another port.
func CORS(origin string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Origin") == origin {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
Two details are easy to miss. writeJSON sets the content type before the status, because headers after WriteHeader are ignored. And the empty list is replaced with []Note{} when the store returns nil, so a client always receives [] and never null.
CORS and the dev proxy
In development the page is served by Vite on port 5173 and the API by Go on port 8080. A browser treats those as two origins, so the API must answer the preflight and set Access-Control-Allow-Origin to exactly the origin of the page. The middleware does that, and answers OPTIONS with 204 without calling a handler.
The frontend can avoid CORS entirely with the Vite proxy from the next page: the browser calls /api/notes on port 5173, Vite forwards it to 8080 on the server side, and no cross-origin request exists. The middleware stays for the case where a developer runs the frontend on another port or a preview server, and it is the reason a curl with an Origin header shows the three headers below.
The tests
The tests call the handler directly with httptest, so no port is opened. The table covers the error paths, and the CORS test checks the preflight and the header.
package notes
import (
"bytes"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
func newServer(t *testing.T) http.Handler {
t.Helper()
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return Handler(NewMemory(), log)
}
func do(t *testing.T, srv http.Handler, method, path, body string) *httptest.ResponseRecorder {
t.Helper()
var reader io.Reader
if body != "" {
reader = bytes.NewBufferString(body)
}
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest(method, path, reader))
return rec
}
func TestCreateAndList(t *testing.T) {
srv := newServer(t)
rec := do(t, srv, "POST", "/api/notes", `{"title":"first","body":"hello"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("POST status = %d, want 201: %s", rec.Code, rec.Body)
}
var created Note
if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil {
t.Fatal(err)
}
if created.ID == 0 || created.Title != "first" {
t.Errorf("created = %+v, want a note with an id and the title", created)
}
rec = do(t, srv, "GET", "/api/notes", "")
if rec.Code != http.StatusOK {
t.Fatalf("GET status = %d, want 200", rec.Code)
}
var list []Note
if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil {
t.Fatal(err)
}
if len(list) != 1 || list[0].Title != "first" {
t.Errorf("list = %+v, want one note titled first", list)
}
}
func TestErrors(t *testing.T) {
srv := newServer(t)
cases := []struct {
name string
method string
path string
body string
want int
}{
{"missing note", "GET", "/api/notes/99", "", http.StatusNotFound},
{"bad id", "GET", "/api/notes/abc", "", http.StatusBadRequest},
{"no title", "POST", "/api/notes", `{"body":"x"}`, http.StatusUnprocessableEntity},
{"bad json", "POST", "/api/notes", `{"title":`, http.StatusBadRequest},
{"unknown field", "POST", "/api/notes", `{"title":"x","extra":1}`, http.StatusBadRequest},
{"unknown endpoint", "GET", "/api/nothing", "", http.StatusNotFound},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := do(t, srv, tc.method, tc.path, tc.body)
if rec.Code != tc.want {
t.Errorf("%s %s = %d, want %d: %s", tc.method, tc.path, rec.Code, tc.want, rec.Body)
}
var payload map[string]string
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatalf("error body is not JSON: %s", rec.Body)
}
if payload["error"] == "" {
t.Errorf("error body = %v, want an error field", payload)
}
})
}
}
func TestDelete(t *testing.T) {
srv := newServer(t)
rec := do(t, srv, "POST", "/api/notes", `{"title":"gone"}`)
var created Note
json.Unmarshal(rec.Body.Bytes(), &created)
path := "/api/notes/" + jsonNumber(created.ID)
if rec := do(t, srv, "DELETE", path, ""); rec.Code != http.StatusNoContent {
t.Fatalf("DELETE status = %d, want 204", rec.Code)
}
if rec := do(t, srv, "DELETE", path, ""); rec.Code != http.StatusNotFound {
t.Errorf("second DELETE status = %d, want 404", rec.Code)
}
}
func TestCORS(t *testing.T) {
log := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := CORS("http://localhost:5173", Handler(NewMemory(), log))
req := httptest.NewRequest("OPTIONS", "/api/notes", nil)
req.Header.Set("Origin", "http://localhost:5173")
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Errorf("preflight status = %d, want 204", rec.Code)
}
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "http://localhost:5173" {
t.Errorf("Allow-Origin = %q, want the dev origin", got)
}
}
func jsonNumber(id int64) string {
data, _ := json.Marshal(id)
return string(data)
}
go vet ./...
go test -v ./...
? example.com/notesweb/cmd/server [no test files]
=== RUN TestCreateAndList
--- PASS: TestCreateAndList (0.00s)
=== RUN TestErrors
=== RUN TestErrors/missing_note
=== RUN TestErrors/bad_id
=== RUN TestErrors/no_title
=== RUN TestErrors/bad_json
=== RUN TestErrors/unknown_field
=== RUN TestErrors/unknown_endpoint
--- PASS: TestErrors (0.00s)
--- PASS: TestErrors/missing_note (0.00s)
--- PASS: TestErrors/bad_id (0.00s)
--- PASS: TestErrors/no_title (0.00s)
--- PASS: TestErrors/bad_json (0.00s)
--- PASS: TestErrors/unknown_field (0.00s)
--- PASS: TestErrors/unknown_endpoint (0.00s)
=== RUN TestDelete
--- PASS: TestDelete (0.00s)
=== RUN TestCORS
--- PASS: TestCORS (0.00s)
PASS
ok example.com/notesweb/internal/notes 0.007s
? example.com/notesweb/web [no test files]
Built and run here
The binary was built with the placeholder frontend of the next page, started on a loopback port with a fresh database, and driven with curl:
go build -o bin/server ./cmd/server
./bin/server -addr 127.0.0.1:18080 -db /tmp/notes-demo.db &
curl -s -X POST -d '{"title":"first note","body":"hello from curl"}' \
http://127.0.0.1:18080/api/notes
{"id":1,"title":"first note","body":"hello from curl"}
curl -s http://127.0.0.1:18080/api/notes
curl -s http://127.0.0.1:18080/api/notes/99 -w ' [%{http_code}]\n'
[{"id":1,"title":"first note","body":"hello from curl"}]
{"error":"note not found"} [404]
curl -s -D - -o /dev/null -H 'Origin: http://localhost:5173' \
http://127.0.0.1:18080/api/notes | grep -i 'access-control\|HTTP/'
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin: http://localhost:5173
The delete returns 204 and an interrupting signal shuts the server down with the five-second budget from main:
curl -s -o /dev/null -w 'status %{http_code}\n' -X DELETE \
http://127.0.0.1:18080/api/notes/1
kill -INT <pid>
status 204
time=2026-11-18T03:29:50.160Z level=INFO msg=listening addr=127.0.0.1:18080 db=/tmp/notes-demo.db
time=2026-11-18T03:29:51.250Z level=INFO msg="note created" id=1
time=2026-11-18T03:30:12.816Z level=INFO msg=stopped
What this backend does not do
There is no authentication, no pagination, no rate limit and no migration tool: the table is created with IF NOT EXISTS and a second schema change would need a real migration. Each of those is a lesson of its own: transactions and prepared statements, schema migrations, CORS and a dev proxy and timeouts, body limits and slow clients. What the project does show is the shape: one interface for storage, one router, one error object, one place for CORS and tests that never open a port.
The next page writes the frontend that calls this API: the React frontend.
The code on this page was run with go 1.26.10, modernc.org/sqlite v1.62.0 and curl on Alpine Linux 3.24.3 (x86_64) in a Docker container. The React part was built in the node:22-bookworm image with Node v22.23.3, npm 10.9.9, vite 6.4.6, react 19.3.1, react-dom 19.3.1, typescript 5.7.3, @vitejs/plugin-react 4.7.0 and @types/react 19.3.0, and the frontend page shows that build.
Article author: Arthur Isaev