Skip to content

Your First Route ​

Add GET /api/v1/users/:id to return a user as JSON. Put the lookup in a service so you can test it separately.

Prerequisites ​

Continue in the Quickstart Project with forj dev running. Run the commands below from the Project root in a second terminal. Use your configured API_HTTP_PORT in place of 3000 if you changed it. An App you already have also works if it has Web API enabled and no users controller.

Step 1: Scaffold the Controller ​

Generate internal/users/controller.go. The command also registers the constructor in app/wire/inject_http_controllers_app.go and exposes the routes through app/routes.go.

bash
forj make:controller users --no-open

Step 2: Add the Service ​

After forj dev rebuilds, request the generated route.

bash
curl http://localhost:3000/api/v1/users
# Hello from users controller

The service returns a fixed record for user 42 so you can try the route without a database.

Create or replace internal/users/service.go:

go
// Package users keeps user behavior independent from HTTP and infrastructure details.
package users

import (
	"context"
	"errors"
)

// ErrUserNotFound lets transports handle missing users without depending on repository details.
var ErrUserNotFound = errors.New("user not found")

// User keeps the application response independent from transport and persistence models.
type User struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

// Service keeps user lookup rules outside the HTTP controller.
type Service struct{}

// NewService keeps construction explicit so Wire and tests use the same entry point.
func NewService() *Service {
	return &Service{}
}

// Find centralizes lookup rules so transports do not duplicate input behavior.
func (*Service) Find(_ context.Context, id string) (User, error) {
	if id != "42" {
		return User{}, ErrUserNotFound
	}

	return User{
		ID:    "42",
		Name:  "Ada Lovelace",
		Email: "[email protected]",
	}, nil
}

Step 3: Replace the Starter Controller ​

Use the existing controller registration to serve GET /users/:id. The controller reads the path parameter, calls the service, and turns the result into an HTTP response.

Create or replace internal/users/controller.go:

go
// Package users keeps HTTP translation separate from user lookup behavior.
package users

import (
	"errors"
	"net/http"

	"github.com/goforj/web"
)

// Controller keeps HTTP translation separate from user lookup behavior.
type Controller struct {
	service *Service
}

// NewController makes the service dependency explicit for Wire and focused tests.
func NewController(service *Service) *Controller {
	return &Controller{service: service}
}

// Routes keeps the users HTTP surface discoverable by the App router.
func (c *Controller) Routes() []web.Route {
	return []web.Route{
		web.NewRoute(http.MethodGet, "/users/:id", c.Show),
	}
}

// Show translates the service result into the public HTTP contract.
func (c *Controller) Show(ctx web.Context) error {
	user, err := c.service.Find(ctx.Context(), ctx.Param("id"))
	if errors.Is(err, ErrUserNotFound) {
		return ctx.JSON(http.StatusNotFound, map[string]string{
			"error": "user not found",
		})
	}
	if err != nil {
		return err
	}

	return ctx.JSON(http.StatusOK, user)
}

Step 4: Provide the Service ​

The controller's constructor now needs *users.Service. Import the users package so you can register its constructor. Replace your/module with the module path in go.mod.

Update app/wire/inject_services_app.go so it includes:

go
	"your/module/internal/runtime"
	"your/module/internal/users"

Step 5: Add the Service Provider ​

Add users.NewService to appSet so Wire can construct the controller. The build regenerates app/wire/wire_gen.go from this provider set.

Update app/wire/inject_services_app.go so it includes:

go
users.NewService,
app.NewLifecycleRegistry,

Step 6: Add a Service Test ​

Test the lookup directly by calling the service with a known ID and an empty ID.

Create or replace internal/users/service_test.go:

go
// Package users keeps lookup behavior testable without starting the HTTP runtime.
package users

import (
	"context"
	"errors"
	"testing"
)

// TestServiceFindsUser protects lookup behavior without involving HTTP wiring.
func TestServiceFindsUser(t *testing.T) {
	service := NewService()
	want := User{
		ID:    "42",
		Name:  "Ada Lovelace",
		Email: "[email protected]",
	}

	user, err := service.Find(context.Background(), "42")
	if err != nil {
		t.Fatalf("find user: %v", err)
	}
	if user != want {
		t.Fatalf("user = %+v, want %+v", user, want)
	}
}

// TestServiceRejectsEmptyID keeps missing identifiers from becoming valid lookups.
func TestServiceRejectsEmptyID(t *testing.T) {
	service := NewService()

	_, err := service.Find(context.Background(), "")
	if !errors.Is(err, ErrUserNotFound) {
		t.Fatalf("find user error = %v, want %v", err, ErrUserNotFound)
	}
}

Verify the Route ​

bash
forj route:list

Look for this path:

text
/api/v1/users/:id

Try the Route ​

Wait for forj dev to finish rebuilding, then request the endpoint from the same second terminal.

bash
curl http://localhost:3000/api/v1/users/42

The response contains Ada's sample record.

json
{"id":"42","name":"Ada Lovelace","email":"[email protected]"}

Operations ​

Operational notes:

  • When enabled, access logs record requests to the route, metrics include the route, and Inspect capture shows request and response details. Lighthouse can display route and runtime information. See Observe HTTP Behavior.

Common Mistakes ​

Common mistakes

  • If you get a 404, wait for the rebuild and check forj route:list for /api/v1/users/:id. Use the same port as the Quickstart health check.
  • Use web.Context in application handlers. Handlers explains the boundary with the HTTP engine.

Next Steps ​