JSON HTTP handlers in Go

The anatomy of a handler, reading query, path and body input, validating at the edge, struct tags and empty slices, choosing status codes, and testing a handler with httptest.

Learning outcomes

  • Write a response in the right order: headers, status, body.
  • Parse query and path parameters and a JSON body, rejecting NaN, unknown fields and oversized bodies.
  • Tell clamping apart from rejecting, and keep every 4xx a JSON object with an error field.
  • Control JSON output with struct tags, and return [] instead of null.
  • Map service errors to status codes in the handler with errors.Is, and test it with httptest.
Prerequisite conceptsDependency injection

Why HTTP handlers need a clear structure

Your backend now has a MySQL schema, generated sqlc queries, and a database access layer. The next step is exposing that functionality through HTTP endpoints.

An HTTP handler is the boundary between the outside world and your application.

It receives an HTTP request, extracts and validates its inputs, calls application logic, and converts the result into an HTTP response.

For example, the restaurant listing endpoint will accept:

http
GET /v1/restaurants?lat=28.46&lng=77.03&radius_km=5&limit=20

The handler needs to:

  1. Read the query parameters.
  2. Parse their values into appropriate Go types.
  3. Validate the inputs.
  4. Call the restaurant service.
  5. Translate errors into HTTP status codes.
  6. Return a JSON response.

Keeping these responsibilities in the handler makes the HTTP layer predictable while allowing your service and database layers to remain independent of HTTP.

Understanding the anatomy of a handler

Go's standard net/http package defines the handler function shape:

go
func(w http.ResponseWriter, r *http.Request)

The two parameters have different responsibilities.

http.ResponseWriter

Used to construct the response sent to the client. You can set response headers, choose the status code, and write the response body.

*http.Request

Contains information about the incoming request, including:

  • HTTP method.
  • URL and query parameters.
  • Request headers.
  • Request body.
  • Context and cancellation information.

A handler doesn't need a framework to perform these operations. chi provides routing and middleware, while the actual HTTP handling uses Go's standard library.

Writing an HTTP response

An HTTP response is composed of three important parts:

  1. Headers.
  2. Status code.
  3. Body.

Consider a successful JSON response:

go
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
	"message": "success",
})

The order matters.

First, set the headers. Then write the status code. Finally, write the body.

Once the response has been committed, you cannot change its status or headers.

For example, calling Write before WriteHeader implicitly commits HTTP 200 OK. A later attempt to return HTTP 400 will not change the response status.

Similarly, calling WriteHeader more than once produces a superfluous response.WriteHeader warning, and the second status cannot replace the first.

Reusing httpx.WriteJSON

Your project already has a helper from Week 1:

go
httpx.WriteJSON(w, status, v)

It performs the response-writing steps consistently:

  1. Sets Content-Type: application/json.
  2. Writes the requested status.
  3. Encodes the supplied value using json.NewEncoder(w).Encode(v).

Use it instead of repeating the same response boilerplate in every handler.

For example:

go
httpx.WriteJSON(w, http.StatusOK, map[string]string{
	"message": "success",
})

Your course rule is that every 4xx response must be JSON and contain an error field.

A reusable helper makes it easier to enforce this consistently.

Reading input from HTTP requests

Different parts of an HTTP request carry different types of input.

You will primarily work with query parameters, path parameters, and JSON request bodies.

Query parameters

The restaurant listing endpoint receives its filters through the URL:

/v1/restaurants?lat=28.46&lng=77.03&radius_km=5&limit=20

Use:

go
query := r.URL.Query()

latValue := query.Get("lat")
lngValue := query.Get("lng")
radiusValue := query.Get("radius_km")
limitValue := query.Get("limit")
cursor := query.Get("cursor")

r.URL.Query() returns the URL's query parameters as a url.Values map.

Get retrieves the first value associated with a parameter name. If the parameter doesn't exist, it returns an empty string.

This is important because query parameters arrive as strings. Your application must explicitly convert them into the types expected by the service.

Parsing numeric parameters

Use strconv.ParseFloat for floating-point inputs:

go
lat, err := strconv.ParseFloat(latValue, 64)
if err != nil {
	return errors.New("invalid latitude")
}

Similarly, use strconv.Atoi for integer inputs:

go
limit, err := strconv.Atoi(limitValue)
if err != nil {
	return errors.New("invalid limit")
}

A successful parse only tells you that the input is syntactically valid. It doesn't mean the value makes sense.

For latitude, the valid range is -90 to 90. Longitude must be between -180 and 180.

There is another subtlety: ParseFloat accepts special values such as NaN and infinity. Ordinary range comparisons are insufficient to reject NaN because comparisons with NaN are false.

For geographic values, explicitly check that the result is finite using math.IsNaN and math.IsInf.

Validating and normalising inputs

For your restaurant listing endpoint, use these rules:

ParameterDefaultValidation
latNoneRequired, -90 to 90
lngNoneRequired, -180 to 180
radius_km5Must be greater than 0 and at most 50
limit20Malformed values rejected; valid integers clamped to 1 through 50
cursorEmptyOptional, interpreted by the pagination layer

Notice the different treatment of limit.

Suppose the client requests:

?limit=1000

You could reject it with HTTP 400, but your API contract says to clamp it instead.

The result becomes 50.

In Go 1.25, you can use the built-in min and max functions:

go
limit = min(max(limit, 1), 50)

However, a malformed value such as:

?limit=abc

must still be rejected.

Clamping applies only after successful numeric parsing.

Likewise, an invalid radius should not silently become the default. The default applies when the parameter is omitted, not when the user supplies an invalid value.

The general principle is:

Parsing determines whether a value has the expected representation. Validation determines whether that value is acceptable.

Path parameters

Some endpoints identify a resource using the URL path.

For example:

GET /v1/restaurants/42

With chi, retrieve the path parameter using:

go
id := chi.URLParam(r, "id")

You will still need to parse and validate it:

go
restaurantID, err := strconv.ParseUint(id, 10, 64)
if err != nil || restaurantID == 0 {
	badRequest(w, "invalid restaurant id")
	return
}

The route itself is registered using:

go
r.Get("/v1/restaurants/{id}", handler.Get)

chi matches the path and makes the captured value available through URLParam.

JSON request bodies

GET endpoints commonly receive input through query parameters. POST endpoints often accept a JSON body.

For example, the menu-pricing endpoint in module 5 receives:

json
{
  "item_id": 1,
  "size": "M",
  "chosen": { "1": [2], "2": [3, 5] },
  "qty": 2
}

Use json.NewDecoder to decode the body into a typed structure:

go
var req struct {
	ItemID uint64             `json:"item_id"`
	Size   string             `json:"size"`
	Chosen map[string][]int64 `json:"chosen"`
	Qty    int                `json:"qty"`
}

if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
	badRequest(w, "invalid JSON body")
	return
}

For production request handlers, add two protections:

Limit the request body size

go
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)

This limits the body to 1 MiB in this example.

Reject unknown fields

go
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()

This prevents accidentally accepting misspelled or unexpected JSON fields.

You should also reject trailing JSON values by attempting a second decode and requiring io.EOF.

These protections will be useful when implementing POST /v1/menu/price in Module 5.

JSON struct tags and response design

Your Go structures need to map cleanly to the JSON format expected by API clients.

JSON struct tags control how exported Go fields are encoded and decoded.

For example:

go
type Restaurant struct {
	ID        int64   `json:"id"`
	Name      string  `json:"name"`
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
}

Without these tags, Go would use field names such as ID and Latitude, which may not match your API contract.

The omitempty option

Consider:

go
type ListResponse struct {
	Items      []Restaurant `json:"items"`
	NextCursor string       `json:"next_cursor,omitempty"`
}

The omitempty option tells the JSON encoder to omit a field when it contains its zero value.

An empty string would therefore cause next_cursor to disappear.

For your restaurant listing response, this is undesirable.

The API must consistently return:

json
{
  "items": [],
  "next_cursor": ""
}

Even when there is no next page.

Use:

go
type ListResponse struct {
	Items      []Restaurant `json:"items"`
	NextCursor string       `json:"next_cursor"`
}

Exported and unexported fields

The standard JSON encoder only processes exported struct fields.

For example:

go
type Restaurant struct {
	ID   uint64 `json:"id"`
	Name string `json:"name"`

	internalNote string
}

internalNote is unexported and is not included in the JSON output.

A JSON tag cannot make an unexported field available to the encoder.

How Go values become JSON

Some useful mappings:

Go valueJSON representation
int64(42)42
float64(12.5)12.5
string("Pizza")"Pizza"
map[string]stringJSON object
nil slicenull
Empty initialized slice[]
Empty string""

The distinction between nil and empty slices is particularly important for collection endpoints.

Compare:

go
var items []Restaurant

with:

go
items := make([]Restaurant, 0)

The first encodes as:

json
null

The second encodes as:

json
[]

For API collections, prefer an initialized empty slice when there are no results. Clients can then consistently treat items as an array.

Choosing the right HTTP status code

HTTP status codes communicate the result of an operation to the client.

Your API uses the following conventions:

StatusMeaningExample
200OKRestaurant listing or successful login
201CreatedSuccessful signup or order creation
400Bad RequestInvalid query parameter or cursor
401UnauthorizedMissing or invalid authentication
403ForbiddenAuthenticated user lacks permission
404Not FoundRequested restaurant does not exist
409ConflictDuplicate resource or conflicting state
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected database or application failure
501Not ImplementedPlaceholder endpoint

These are HTTP status codes that should reflect the actual outcome of the request.

A particularly important distinction:

  • HTTP 401 means the caller has not provided valid authentication.
  • HTTP 403 means the caller is authenticated but not allowed to perform the operation.

Similarly, a malformed cursor is a client input error and must return 400. It must not become a 500 merely because parsing failed inside the service layer.

Error mapping belongs in the handler

Your service should return meaningful Go errors rather than HTTP responses.

For example, suppose the service returns a sentinel error:

go
var ErrNotFound = errors.New("restaurant not found")

It might wrap that error with additional context:

go
return Restaurant{}, fmt.Errorf(
	"get restaurant %d: %w",
	id,
	ErrNotFound,
)

The handler can identify it using errors.Is:

go
if errors.Is(err, ErrNotFound) {
	httpx.WriteJSON(w, http.StatusNotFound,
		map[string]string{"error": "not_found"})
	return
}

Other unexpected errors should produce a generic 500 response.

The important distinction is that the service describes what happened, while the handler decides how that outcome should be represented over HTTP.

Separating handlers and services

Your restaurant package follows this structure:

internal/restaurant/handler.go
internal/restaurant/service.go

The handler is responsible for HTTP concerns:

  • Reading and parsing URL parameters.
  • Validating client input.
  • Calling the service.
  • Mapping errors into status codes.
  • Writing JSON responses.

The service is responsible for application logic:

  • Executing business operations.
  • Coordinating database queries.
  • Applying domain rules.
  • Returning meaningful results and errors.

The handler receives its service through a constructor:

go
type Handler struct {
	svc *Service
}

func NewHandler(svc *Service) *Handler {
	return &Handler{svc: svc}
}

This uses the dependency injection approach introduced in Lesson 2.5.

The handler doesn't create its own database connection or initialise its service internally.

This separation also means that HTTP parsing can be tested independently of database behaviour.

What the restaurant List handler does

Your implementation will have:

go
func (h *Handler) List(
	w http.ResponseWriter,
	r *http.Request,
)

It should follow this sequence:

  1. Extract lat and lng.
  2. Parse and validate both coordinates.
  3. Extract radius_km, applying the default of 5 when omitted.
  4. Parse the limit, defaulting to 20 and clamping valid integers to 1 through 50.
  5. Extract the optional cursor.
  6. Construct the service input.
  7. Call h.svc.List(r.Context(), n).
  8. Return a JSON 500 response for unexpected service errors.
  9. Otherwise, return HTTP 200 with the items and next cursor.

The service call should receive the request context rather than a newly created background context.

Any database operations performed by the service should derive their own bounded contexts according to the 500 ms read-timeout requirement from Lesson 2.4.

A useful response structure is:

go
type ListResponse struct {
	Items      []Restaurant `json:"items"`
	NextCursor string       `json:"next_cursor"`
}

Make sure Items is initialized when there are no results.

Keeping internal errors private

Suppose a database query fails with a detailed MySQL error.

Returning that error directly to the client might expose table names, SQL details, database configuration, or implementation information.

Instead, return:

json
{
  "error": "internal_error"
}

Use server-side logs for diagnostics.

Testing handlers without starting a server

Go provides net/http/httptest for testing HTTP handlers directly.

You don't need to start a real TCP server just to test how a handler parses a request or formats a response.

Two useful functions are:

  • httptest.NewRequest: Constructs an HTTP request.
  • httptest.NewRecorder: Captures the response written by the handler.

For example:

go
func TestListBadLatitude(t *testing.T) {
	req := httptest.NewRequest(
		http.MethodGet,
		"/v1/restaurants?lat=invalid&lng=77.03",
		nil,
	)

	rec := httptest.NewRecorder()

	handler := NewHandler(NewService(fakeQueries{}))
	handler.List(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected 400, got %d", rec.Code)
	}

	var body map[string]string
	if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
		t.Fatal(err)
	}

	if body["error"] == "" {
		t.Fatal("expected an error field")
	}
}

Here, the handler is invoked directly with an invalid latitude.

The test checks the status code and verifies that the response contains an error.

You can use the same approach for:

  • Missing required parameters.
  • Invalid coordinate ranges.
  • Invalid radius.
  • Malformed limits.
  • Limit clamping.
  • Missing restaurants.
  • Unexpected service failures.
  • Empty collection responses.

fakeQueries is a small struct in the test file that implements the service's Queries interface and returns predetermined rows or errors, so the real service runs without MySQL.

This keeps handler tests fast and focused on HTTP behaviour.

Knowledge assessment

Question 1 of 4

Consider the following HTTP handler code. What happens when the response body is written before the status code?

Pick an answer, then say how sure you are.

Practical applications

Exercise 2.10: GET /v1/restaurants with a cursor

You'll implement the first complete restaurant-listing handler.

It will accept geographic coordinates, radius, page size, and an optional cursor. You'll validate the incoming parameters, call your restaurant service, and return a consistent JSON response with the next cursor.

The handler will use the same response helper and error-mapping conventions established here.

Module 4: Menu endpoints

Your menu endpoint will retrieve restaurant information and assemble menu items, sizes, groups, and options into a JSON response.

You'll use the same separation between HTTP parsing, service logic, and database queries.

Module 5: Menu pricing endpoint

The POST endpoint will accept a JSON request body containing the selected item, size, and options.

You'll reuse the decoding, request-size limits, validation, status-code mapping, and JSON response conventions introduced in this lesson.

By the end of these modules, every endpoint should follow a consistent contract: validate input at the HTTP boundary, execute application logic through a service, and return predictable JSON responses.

References

Everything above is explained on this page; these are where it comes from (Go 1.25 net/http and encoding/json, go-chi/chi v5).

Finished Lesson 2.8?