1
0
forked from security/hakurei

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 <cat@gensokyo.uk>
This commit is contained in:
2026-03-11 02:10:40 +09:00
committed by mae
parent 5d6c401beb
commit 6401533cc2

View File

@@ -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,
)
}
}