Files
job-search/internal/httpx/problem.go
T

38 lines
1.1 KiB
Go

// Package httpx holds small HTTP helpers shared by middleware and handlers.
package httpx
import (
"encoding/json"
"net/http"
)
// Problem is an RFC 9457 problem details body.
type Problem struct {
Type string `json:"type,omitempty" validate:"optional"`
Status int `json:"status"`
Title string `json:"title"`
Detail string `json:"detail,omitempty" validate:"optional"`
Instance string `json:"instance,omitempty" validate:"optional"`
RequestID string `json:"requestId,omitempty" validate:"optional"`
}
// WriteProblem writes a problem+json error response.
func WriteProblem(
w http.ResponseWriter, r *http.Request, status int, detail string,
) {
problem := Problem{
Type: "about:blank",
Title: http.StatusText(status),
Status: status,
Detail: detail,
}
if r != nil {
problem.RequestID = RequestID(r.Context())
}
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
json.NewEncoder(w).Encode(problem) //nolint:errcheck,gosec // the client may have gone
}