From 0a2d9dbe425ef91fec9cbbc3fe06a721e292682d Mon Sep 17 00:00:00 2001 From: Ophestra Date: Wed, 11 Mar 2026 02:10:40 +0900 Subject: [PATCH] cmd/pkgserver: log instead of write encoding error This message is unlikely to be useful to the user, and output may be partially written at this point, causing the error to be even less intelligible. Signed-off-by: Ophestra --- cmd/pkgserver/api.go | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/cmd/pkgserver/api.go b/cmd/pkgserver/api.go index 810c99e4..5c850dc9 100644 --- a/cmd/pkgserver/api.go +++ b/cmd/pkgserver/api.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "log" "net/http" "path" "strconv" @@ -32,9 +33,8 @@ func serveInfo(w http.ResponseWriter, _ *http.Request) { infoPayload.Count = int(rosa.PresetUnexportedStart) infoPayload.HakureiVersion = info.Version() }) - w.WriteHeader(http.StatusOK) // TODO(mae): cache entire response if no additional fields are planned - WritePayload(w, infoPayload) + writeAPIPayload(w, infoPayload) } func (index *packageIndex) serveStatus() http.HandlerFunc { @@ -73,7 +73,6 @@ func (index *packageIndex) serveStatus() http.HandlerFunc { } w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - w.WriteHeader(http.StatusOK) _, err := io.Copy(w, bytes.NewReader(pk.status)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -104,7 +103,7 @@ func (index *packageIndex) serveGet() http.HandlerFunc { } values := index.sorts[sort][i:min(i+limit, len(index.sorts[sort]))] // TODO(mae): remove count field - WritePayload(w, &struct { + writeAPIPayload(w, &struct { Count int `json:"count"` Values []*metadata `json:"values"` }{len(values), values}) @@ -120,13 +119,19 @@ func apiRoutes(mux *http.ServeMux, index *packageIndex) { mux.HandleFunc("GET /status/", index.serveStatus()) } -func WritePayload(w http.ResponseWriter, payload any) { +// writeAPIPayload sets headers common to API responses and encodes payload as +// JSON for the response body. +func writeAPIPayload(w http.ResponseWriter, payload any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Header().Set("Pragma", "no-cache") w.Header().Set("Expires", "0") - err := json.NewEncoder(w).Encode(payload) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + + if err := json.NewEncoder(w).Encode(payload); err != nil { + log.Println(err) + http.Error( + w, "cannot encode payload, contact maintainers", + http.StatusInternalServerError, + ) } }