pkg/gateway/problem/problem.go
Source
- Package:
problem - File:
pkg/gateway/problem/problem.go - GitHub: https://github.com/theroutercompany/api_router/blob/main/pkg/gateway/problem/problem.go
Overview
What: Helpers for emitting RFC 7807 Problem+JSON responses with gateway-specific fields (notably traceId).
Why: Standardizes error responses across handlers and middleware so clients see consistent shape and tracing metadata.
How: Defines a Response struct and a Write helper that encodes it as application/problem+json.
Contents
Imports
import block 1
import (
"encoding/json"
"net/http"
)
Types
type block 1
type Response struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
TraceID string `json:"traceId,omitempty"`
}
Response
What: JSON shape for the gateway's Problem+JSON responses.
Why: Provides a typed, consistent error payload including trace correlation (traceId) and instance path (instance).
How: Used by Write and referenced by code that wants to emit RFC 7807 style responses.
Functions and Methods
Write
What: Writes an RFC 7807 Problem+JSON response to an http.ResponseWriter.
Why: Centralizes content-type, status, and JSON structure so call sites stay small and consistent.
How: Builds a Response with type set to about:blank, sets headers, writes status code, and JSON-encodes the body.
func Write(w http.ResponseWriter, status int, title, detail, traceID, instance string) {
resp := Response{
Type: "about:blank",
Title: title,
Status: status,
Detail: detail,
Instance: instance,
TraceID: traceID,
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(resp)
}
Walkthrough
The list below documents the statements inside the function body, including nested blocks and inline closures.
- L23:
resp := Response{ Type: "about:blank", Title: title, Status: status, Detail: detail, Instance: instance, TraceID: traceID, }- What: Defines resp.
- Why: Keeps intermediate state available for later steps in the function.
- How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
- L32:
w.Header().Set("Content-Type", "application/problem+json")- What: Calls w.Header().Set.
- Why: Performs side effects or delegates work to a helper.
- How: Executes the expression statement.
- L33:
w.WriteHeader(status)- What: Calls w.WriteHeader.
- Why: Performs side effects or delegates work to a helper.
- How: Executes the expression statement.
- L34:
_ = json.NewEncoder(w).Encode(resp)- What: Assigns _.
- Why: Keeps intermediate state available for later steps in the function.
- How: Evaluates the right-hand side expressions and stores results in the left-hand variables.