Skip to content

Validation ​

Add POST /api/v1/users to the App you built in Your First Route. The new endpoint accepts a display name, email, and password. It returns a sample user so you can work through the request and response without a database.

Map Binding and Validation Separately ​

ctx.Bind decodes the request into a Go value. The controller then checks the decoded fields before calling the service.

What happenedResponse
The request exceeded the route's body limit413 Content Too Large
The body could not be decoded400 Bad Request with invalid_payload
At least one decoded field failed validation422 Unprocessable Entity with validation_failed and field codes
The service returned a user201 Created with the user as JSON

Keep binder errors private. A stable error code lets clients handle bad input without relying on the adapter's error text.

Define the Service Input ​

Add internal/users/create_user.go. The service takes ordinary Go fields and returns the User type from the lookup route.

go
package users

import "context"

// CreateUserInput carries the normalized request into the service.
type CreateUserInput struct {
	DisplayName string
	Email       string
	Password    string
}

// Create returns a sample user without storing credentials or writing to a database.
func (*Service) Create(_ context.Context, input CreateUserInput) (User, error) {
	return User{ID: "user_123", Name: input.DisplayName, Email: input.Email}, nil
}

A real service can apply business rules and write through a repository. Use the Auth guide when you need account storage and authentication.

Bind, Normalize, and Validate ​

Add internal/users/store.go. The request type defines the JSON field names. Store maps errors to responses and passes the request context to the service.

go
package users

import (
	"errors"
	"net/http"
	"net/mail"
	"strings"
	"unicode/utf8"

	"github.com/goforj/web"
)

type createUserRequest struct {
	DisplayName string `json:"display_name"`
	Email       string `json:"email"`
	Password    string `json:"password"`
}

type errorResponse struct {
	Error  string            `json:"error"`
	Fields map[string]string `json:"fields,omitempty"`
}

// Store creates a user only after the request has passed validation.
func (c *Controller) Store(ctx web.Context) error {
	var request createUserRequest
	if err := ctx.Bind(&request); err != nil {
		var tooLarge *http.MaxBytesError
		if errors.As(err, &tooLarge) {
			return ctx.Text(http.StatusRequestEntityTooLarge, http.StatusText(http.StatusRequestEntityTooLarge))
		}
		return ctx.JSON(http.StatusBadRequest, errorResponse{Error: "invalid_payload"})
	}

	input, fields := request.input()
	if len(fields) != 0 {
		return ctx.JSON(http.StatusUnprocessableEntity, errorResponse{
			Error:  "validation_failed",
			Fields: fields,
		})
	}

	user, err := c.service.Create(ctx.Context(), input)
	if err != nil {
		return err
	}
	return ctx.JSON(http.StatusCreated, user)
}

// input normalizes identifiers and leaves credential bytes intact.
func (r createUserRequest) input() (CreateUserInput, map[string]string) {
	input := CreateUserInput{
		DisplayName: strings.TrimSpace(r.DisplayName),
		Email:       strings.ToLower(strings.TrimSpace(r.Email)),
		Password:    r.Password,
	}
	fields := make(map[string]string)
	if input.DisplayName == "" {
		fields["display_name"] = "required"
	}
	if input.Email == "" {
		fields["email"] = "required"
	} else if address, err := mail.ParseAddress(input.Email); err != nil || address.Address != input.Email {
		fields["email"] = "invalid_format"
	}
	if input.Password == "" {
		fields["password"] = "required"
	} else if utf8.RuneCountInString(input.Password) < 12 {
		fields["password"] = "too_short"
	}
	return input, fields
}

The example treats email addresses as case-insensitive identifiers and checks for a bare address. Pass passwords through byte for byte so callers can use meaningful whitespace. The example counts whitespace toward the length minimum. Apply stricter credential rules explicitly if your application needs them.

Field errors use the request's JSON keys and one code per field. Check required first so clients can distinguish missing input from a format or length problem.

Register the POST Route ​

In internal/users/controller.go, add "github.com/goforj/web/webmiddleware" to the imports. Update Routes to register the lookup and creation endpoints.

go
// Routes exposes the users lookup and creation handlers.
func (c *Controller) Routes() []web.Route {
	return []web.Route{
		web.NewRoute(http.MethodGet, "/users/:id", c.Show),
		web.NewRoute(http.MethodPost, "/users", c.Store, webmiddleware.BodyLimit("16KB")).
			WithMiddlewareNames("webmiddleware.BodyLimit"),
	}
}

The body limit middleware rejects a declared size over 16 KiB before Store runs. It also caps reads when the size is unknown. In that case Store maps a size error during binding to 413.

Test Invalid and Valid Requests ​

Wait for forj dev to finish rebuilding. In a second terminal, use the same port as in Your First Route. Send an invalid request and check the 422 status and field codes.

bash
curl -i http://localhost:3000/api/v1/users \
  -H 'Content-Type: application/json' \
  --data '{"display_name":" ","email":"x","password":"short"}'
json
{"error":"validation_failed","fields":{"display_name":"required","email":"invalid_format","password":"too_short"}}

Send valid fields and check the 201 status and normalized response.

bash
curl -i http://localhost:3000/api/v1/users \
  -H 'Content-Type: application/json' \
  --data '{"display_name":"  Ada Lovelace  ","email":" [email protected] ","password":"  example passphrase  "}'
json
{"id":"user_123","name":"Ada Lovelace","email":"[email protected]"}

Add HTTP tests for both routes to cover the body limit, malformed JSON, field errors, and the successful response.

Validation Boundary ​

Check required fields, field formats, and path or query parameters at the HTTP boundary. Keep rules that depend on persisted data, permissions, or workflows in application services. Pass ctx.Context() so cancellation and deadlines reach those services and their dependencies.

Next Steps ​

Next, enable SQLite in the same Project. You'll create a photos table and add endpoints that save and list records.

See Responses and Error Handling for how Store and Show turn service results into HTTP responses.