package main import ( "encoding/json" "net/http" ) type ApiError struct { Err string Status int } func (e ApiError) Error() string { return e.Err } type apiFunc func(http.ResponseWriter, *http.Request) error func MakeHTTPHandler(f apiFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if err := f(w, r); err != nil { if e, ok := err.(ApiError); ok { WriteJSON(w, e.Status, e) return } WriteJSON(w, 500, ApiError{Err: err.Error(), Status: http.StatusInternalServerError}) return } } } func StatusAndContent(w http.ResponseWriter, status int, contentType string) { w.Header().Add("Content-Type", contentType) w.WriteHeader(status) } func WriteJSON(w http.ResponseWriter, status int, v any) error { StatusAndContent(w, status, "application/json") return json.NewEncoder(w).Encode(v) } func WritePlain(w http.ResponseWriter, status int, text string) error { StatusAndContent(w, status, "text/plain") _, err := w.Write([]byte(text)) return err } func WriteBlob(w http.ResponseWriter, status int, contentType string, blob []byte) error { StatusAndContent(w, status, contentType) _, err := w.Write(blob) return err }