Build your first module
In this tutorial you build a products module for a shop: each tenant keeps its own catalogue of products with a name, a SKU, a price, a stock count and optional notes. Along the way you touch every layer once, so by the end you know where everything goes.
You will:
- generate the module and read what was generated,
- add a database rule (a SKU is unique per tenant),
- loosen a validation rule and add a business rule in the service,
- record changes in the tenant’s activity log,
- register permissions, wire the routes and call the API,
- write an integration test that proves tenant isolation,
- see your requests in the developer dashboard.
1. Generate the module
The generator takes a module name and a field list and writes a complete, compiling module.
go run ./cmd/app gen module --name=product \ --fields="name:string,sku:string,price:decimal,stock:int,is_active:bool,notes:text?"$ go run ./cmd/app gen module --name=product --fields="name:string,sku:string,price:decimal,stock:int,is_active:bool,notes:text?"wrote migrations/00025_create_products.sqlwrote sql/queries/products.sqlwrote internal/modules/product/model.gowrote internal/modules/product/repository.gowrote internal/modules/product/service.gowrote internal/modules/product/request.gowrote internal/modules/product/handler.gowrote internal/modules/product/routes.gowrote internal/modules/product/service_test.gorunning sqlc generate… doneupdated api/openapi.yaml (1 resources)Module "product" generated.Field types: string, text, int, bigint, bool, decimal, date, datetime,
json. Add ? to make a field nullable (notes:text?). decimal is stored as a bigint in
minor units — 12.50 is 1250 — so money never suffers floating-point rounding.
What you got:
Directorymigrations/
- 00025_create_products.sql the table, tenant index, soft delete
Directorysql/queries/
- products.sql tenant-filtered CRUD queries
Directoryinternal/
Directorydbgen/ regenerated by sqlc
- …
Directorymodules/product/
- model.go the Product struct and row mapping
- repository.go Repository interface + sqlc implementation
- service.go business rules and tenancy
- request.go request/response DTOs
- handler.go HTTP actions (index, show, store, update, destroy)
- routes.go routes, each with its permission
- service_test.go unit tests with a fake repository
- api/openapi.yaml the /api/v1/product section, added for you
Open routes.go — this is the module’s public surface:
func (h *Handler) RegisterRoutes(r chi.Router) { r.With(h.can(PermView)).Get("/product", h.index) r.With(h.can(PermView)).Get("/product/{id}", h.show) r.With(h.can(PermCreate)).Post("/product", h.store) r.With(h.can(PermUpdate)).Patch("/product/{id}", h.update) r.With(h.can(PermDelete)).Delete("/product/{id}", h.destroy)}Every route declares its permission. The generated module is tenant-scoped: every query in
products.sql filters on tenant_id, and the service refuses to run without a tenant.
2. Add a database rule: a SKU is unique per tenant
The migration is yours to edit until it has been applied. Add a unique index on the SKU, per tenant, ignoring soft-deleted rows (so a deleted product’s SKU can be reused):
CREATE INDEX products_tenant_id_idx ON products (tenant_id);CREATE UNIQUE INDEX products_tenant_sku_unique ON products (tenant_id, lower(sku)) WHERE deleted_at IS NULL;Apply it:
go run ./cmd/app migratego run ./cmd/app migrate:status # 00025_create_products.sql: applied3. Adjust validation
Open request.go. The generator marks every non-nullable field required — but for numbers
required means “not zero”, and a product with 0 in stock is perfectly valid. Change the two
number rules to gte=0:
type InsertUpdateRequest struct { Name string `json:"name" validate:"required,min=1,max=255"` Sku string `json:"sku" validate:"required,min=1,max=255"` Price int64 `json:"price" validate:"required"` Stock int32 `json:"stock" validate:"required"` Price int64 `json:"price" validate:"gte=0"` // minor units: 1250 = 12.50 Stock int32 `json:"stock" validate:"gte=0"` IsActive bool `json:"is_active" validate:"omitempty"` Notes *string `json:"notes" validate:"omitempty,max=255"`}h.Bind runs these rules and answers 422 with a per-field errors map when they fail — the
same as a Laravel form request. Because the request shape changed, refresh the module’s OpenAPI
section:
go run ./cmd/app gen openapi --module=product4. Add a business rule and an activity entry
Structural rules (“is this a number?”) live on the request. Business rules live in the service, where every caller — HTTP, CLI, a queue job — gets them.
Two changes in service.go:
- When the unique index rejects a duplicate SKU, answer with a clear validation error on the
skufield instead of a generic 409. - Record the change in the tenant’s activity log, so tenant admins can see who created what.
type Service struct { repo Repository activity *activity.Recorder}
// NewService creates the product service.func NewService(repo Repository) *Service { return &Service{repo: repo}}
// WithActivity records product changes in the tenant's activity log.func (s *Service) WithActivity(recorder *activity.Recorder) *Service { s.activity = recorder return s}
// Create creates a product in the effective tenant scope.func (s *Service) Create(ctx context.Context, scope tenancy.Scope, actorID int64, input CreateInput) (*Product, error) { input.TenantID = scope.EffectiveTenantID() if input.TenantID == 0 { return nil, apperr.New(apperr.TenantContextNotResolved, "A tenant context is required.") } input.ActorID = &actorID product, err := s.repo.Create(ctx, input) if apperr.Is(err, apperr.ResourceAlreadyExists) { return nil, apperr.Validation(map[string][]string{"sku": {"This SKU is already in use."}}) } if err != nil { return nil, err } s.activity.Record(ctx, activity.Entry{ TenantID: product.TenantID, Action: "product.created", Subject: "product", SubjectID: product.ID, Changes: map[string]any{"name": product.Name, "sku": product.Sku}, }) return product, nil}Add the import "github.com/Innovix-Matrix-Systems/ims-go-api-starter/internal/modules/activity".
How this works:
- The repository translates Postgres errors with
database.MapError; a unique violation becomesapperr.ResourceAlreadyExists(HTTP 409). The service turns this particular conflict into a field error, because it knows what it means. s.activity.Recordis nil-safe: with no recorder (the generated unit tests) it does nothing, so tests need no setup. The actor, IP address and request id are taken from the context automatically.
5. Register the permissions
The routes need product.view, product.create, product.update and product.delete. Add them
to the catalog — the single list of every permission:
var Catalog = []Permission{ // ── product ─────────────────────────────────────────── {Name: "product.view", Group: "product", Description: "Can view products"}, {Name: "product.create", Group: "product", Description: "Can create products"}, {Name: "product.update", Group: "product", Description: "Can update products"}, {Name: "product.delete", Group: "product", Description: "Can delete products"},Tenant Admin roles are built from a list of permission groups. Add product so every new
tenant’s Admin can manage products:
case "role", "branch", "user", "setting", "activity", "product":Store the new permissions in the database:
go run ./cmd/app permission:sync # Synced 4 permission(s).6. Wire the handler and mount the routes
Nothing is wired by reflection; you connect the module explicitly in two places.
Build the handler in internal/app/wiring.go — add a field to Dependencies and construct
it in NewDependencies:
// Dependencies struct Flags *featureflags.Handler Products *product.Handler
// NewDependencies, inside the deps literal Flags: featureflags.NewHandler(platform.FeatureFlags, checker, kit), Products: product.NewHandler( product.NewService(product.NewRepository(queries)).WithActivity(platform.Activity), checker, kit, ),Mount the routes in internal/app/routes.go, inside the tenant-resolved group — the one
that runs tenancy.Resolve, so every request carries a tenant:
r.Group(func(r chi.Router) { r.Use(tenancy.Resolve(d.TenancyOpts)) // … users, branches, settings … d.Flags.RegisterRoutes(r) d.Products.RegisterRoutes(r)})make dev rebuilds the API as soon as you save. Check the build anytime with go build ./....
7. Call your API
Sign in as the super admin and act inside the seeded tenant (tenant 1, branch 1):
TOKEN=$(curl -s localhost:8080/api/v1/login -H 'Content-Type: application/json' \ -d '{"email":"superadmin@ims.com","password":"123456","device":"tutorial"}' | jq -r .data.token)H=(-H "Authorization: Bearer $TOKEN" -H "X-Acting-Tenant: 1" -H "X-Acting-Branch: 1" -H 'Content-Type: application/json')
curl -s localhost:8080/api/v1/product "${H[@]}" -d '{"name":"Pen","sku":"PEN-1","price":1250,"stock":0}' | jqcurl -s localhost:8080/api/v1/product "${H[@]}" -d '{"name":"Pen","sku":"pen-1","price":900,"stock":3}' | jqcurl -s "localhost:8080/api/v1/product?search=pen" "${H[@]}" | jq$login = Invoke-RestMethod http://localhost:8080/api/v1/login -Method Post -ContentType 'application/json' ` -Body '{"email":"superadmin@ims.com","password":"123456","device":"tutorial"}'$h = @{ Authorization = "Bearer $($login.data.token)"; 'X-Acting-Tenant' = '1'; 'X-Acting-Branch' = '1' }
Invoke-RestMethod http://localhost:8080/api/v1/product -Method Post -Headers $h -ContentType 'application/json' ` -Body '{"name":"Pen","sku":"PEN-1","price":1250,"stock":0}'Invoke-RestMethod "http://localhost:8080/api/v1/product?search=pen" -Headers $hThe first call answers 201 with {"data": {...}}. The second answers 422 — your business
rule at work:
{ "type": "http://localhost:8080/errors/validation-failed", "status": 422, "detail": "The given data was invalid.", "error_code": "VALIDATION_FAILED", "errors": { "sku": ["This SKU is already in use."] }, "instance": "/api/v1/product", "timestamp": "2026-11-20T10:15:04Z"}(The response also carries a title; the shape is the same for every error in the API — see
Validation & errors.)
The list supports ?search=, ?page= and ?per_page= and answers with data, links and
meta for pagination.
Or try it in the API reference
You don’t need curl at all. The generator already added a Products section to
api/openapi.yaml in step 1, and the app serves that file as an interactive reference (Scalar) at
localhost:8080/docs:
- Open
/docs, find Auth → Authenticate with email and password and send it with the super-admin credentials. Copy thetokenfrom the response. - Click Authentication at the top and paste the token as the Bearer token. It is kept across page reloads.
- Open Products → Create a product, fill
X-Acting-Tenant: 1andX-Acting-Branch: 1in the headers, edit the body and press Send.
The page is generated from the same spec that make openapi-check compares with the router, so
whatever you see there is what the API really accepts. Your frontend team can use it the same
way, or generate a typed client from /docs/openapi.yaml. DOCS_ENABLED=false turns it off
in production.
8. Write the tests
The generator already wrote unit tests (service_test.go) that check the service scopes to
the tenant, using a fake repository — they need no database:
go test ./internal/modules/product/Now add an integration test with testkit, which boots the real application against a fresh,
seeded schema — like a Laravel feature test. Prove the happy path, your SKU rule, permissions and,
most importantly, tenant isolation:
package product_test
import ( "fmt" "net/http" "testing"
"github.com/Innovix-Matrix-Systems/ims-go-api-starter/internal/testkit")
func TestProducts(t *testing.T) { app := testkit.New(t) admin := app.User(t) // Admin of the seeded tenant
var created struct { ID int64 `json:"id"` Name string `json:"name"` } app.As(admin).Post("/api/v1/product", `{"name":"Pen","sku":"PEN-1","price":1250,"stock":0}`). Status(t, http.StatusCreated).Data(t, &created)
// The same SKU in the same tenant is a validation error. app.As(admin).Post("/api/v1/product", `{"name":"Pen 2","sku":"pen-1","price":900,"stock":3}`). Status(t, http.StatusUnprocessableEntity)
// Another tenant can never see it. other := app.User(t, testkit.InTenant(app.Tenant(t, "Tenant B"))) path := fmt.Sprintf("/api/v1/product/%d", created.ID) app.As(other).Get(path).Status(t, http.StatusNotFound) app.As(other).Delete(path).Status(t, http.StatusNotFound)
// No permission, no access. viewer := app.User(t, testkit.Role(app.Role(t, "Viewer"))) app.As(viewer).Get("/api/v1/product").Status(t, http.StatusForbidden)}Run it against a test database (each test package gets its own schema, so this is safe to run in parallel with everything else):
export DATABASE_TEST_DSN="postgres://postgres:postgres@127.0.0.1:5432/ims_go_api_test?sslmode=disable"go test -count=1 ./internal/modules/product/$env:DATABASE_TEST_DSN = "postgres://postgres:postgres@127.0.0.1:5432/ims_go_api_test?sslmode=disable"go test -count=1 ./internal/modules/product/9. See it in the dashboard
Open localhost:8080/dev/ and look at what you built:
- Telescope shows each request you made, with the SQL it ran and its timing.
- Inspector → Routes lists
/api/v1/productwith itscan:middleware; filter byproduct. - Inspector → Roles & permissions shows the new
productgroup. - The tenant’s activity feed (
GET /api/v1/activity) has aproduct.createdentry with you as the actor.
10. Finish like a pro
make check # gofmt + vet + lint + unit testsmake gen-check # generated code (sqlc, OpenAPI, docs) is currentmake openapi-check # the spec matches the routerThen commit the module, the migration, the regenerated internal/dbgen and api/openapi.yaml
together.
What you learned
| You did | The rule |
|---|---|
| generated the module | ims gen module gives a tenant-scoped, soft-deleting module that compiles |
| edited the migration | the schema lives only in migrations/; never edit one that has been applied |
changed request.go |
structural validation belongs on the request (validate tags) |
changed service.go |
business rules and activity belong in the service |
edited catalog.go |
every permission is declared once, in Go |
edited wiring.go, routes.go |
everything is wired explicitly; tenant data goes in the resolved group |
wrote a testkit test |
prove isolation: another tenant gets 404 |
Next, read the guides for the parts you’ll use most: Modules, Handlers & routes, Database and Testing.