Skip to content

Requests ​

A handler receives a web.Context for one request. Use it to read HTTP input and obtain the Go context your service needs.

Read a Path or Query Parameter ​

In Your First Route, Show reads the ID from ctx.Param("id"). To let callers ask for just the user's name, add this block in internal/users/controller.go after the lookup succeeds and before the existing JSON response.

go
if ctx.Query("view") == "name" {
	return ctx.JSON(http.StatusOK, map[string]string{"name": user.Name})
}

With forj dev running, request that view from a second terminal. Use your configured HTTP port if you changed it.

bash
curl -fsS 'http://localhost:3000/api/v1/users/42?view=name'
# {"name":"Ada Lovelace"}

ctx.Query("view") returns an empty string when the parameter is absent. The existing response still returns all fields in the default view. Use ctx.Request().URL.Query()["view"] when a request can supply several values for the same key.

Read Headers and Pass Context ​

Read a header with ctx.Header("Content-Type"). For a standard-library API that takes an *http.Request, use ctx.Request(). Pass ctx.Context() to database queries and other cancellable work. Keep HTTP reads and writes in the handler. The standard Go context can cross goroutine boundaries when needed.

Read a JSON Body ​

Set Content-Type: application/json on the client. Use ctx.Bind(&input) in the handler to decode fields into a request struct with json tags. Apply a body limit on routes that read bodies. Treat decoded values as input and check their rules before calling the service.

Next Steps ​

Add the POST endpoint in Validation to decode a body, report field errors, and pass normalized input to the service.