~bigbes/huntsman

ref: 766fa8055977fbe223afd8a84bcf37a3d13bb1ce huntsman/internal/pkg/httputil/response.go -rw-r--r-- 1.1 KiB
766fa805 — Eugene Blikh Add BSD 2-Clause license 7 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Package httputil contains thin JSON-response and error-routing helpers.
package httputil

import (
	"encoding/json"
	"log/slog"
	"net/http"

	"go.bigb.es/auxilia/scribe"

	"sourcecraft.dev/bigbes/huntsman/internal/pkg/apierror"
)

// JSON writes a JSON response with the given status code.
func JSON(w http.ResponseWriter, status int, data any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if data != nil {
		_ = json.NewEncoder(w).Encode(data)
	}
}

// OK is the common 200 path.
func OK(w http.ResponseWriter, data any) { JSON(w, http.StatusOK, data) }

// Error converts err into a Problem response. Internal (5xx) errors are
// logged with the original error message; client errors are not, since
// they're not actionable for the operator.
func Error(w http.ResponseWriter, r *http.Request, err error) {
	problem := apierror.FromError(err)
	if problem.Status >= 500 {
		//nolint:gosec // G706: slog handlers escape attribute values, so r.URL.Path cannot inject newlines into log output.
		slog.Error("internal error", "path", r.URL.Path, scribe.Err(err))
	}
	problem.Write(w)
}