Skip to content

Commit

Permalink
httptransport: add error helper
Browse files Browse the repository at this point in the history
Signed-off-by: Hank Donnay <hdonnay@redhat.com>
  • Loading branch information
hdonnay committed Jan 14, 2022
1 parent 1972a87 commit 55198e8
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions httptransport/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package httptransport

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)

// ApiError writes an untyped (that is, "application/json") error with the
// provided HTTP status code and message.
func apiError(w http.ResponseWriter, code int, f string, v ...interface{}) {
const errheader = `Clair-Error`
h := w.Header()
h.Del("link")
h.Set("content-type", "application/json")
h.Set("x-content-type-options", "nosniff")
h.Set("trailer", errheader)
w.WriteHeader(code)

var buf bytes.Buffer
buf.WriteString(`{"code":"`)
switch code {
case http.StatusBadRequest:
buf.WriteString("bad-request")
case http.StatusMethodNotAllowed:
buf.WriteString("method-not-allowed")
case http.StatusNotFound:
buf.WriteString("not-found")
default:
buf.WriteString("internal-error")
}
buf.WriteByte('"')
if f != "" {
buf.WriteString(`,"message":`)
b, _ := json.Marshal(fmt.Sprintf(f, v...)) // OK use of encoding/json.
buf.Write(b)
}
buf.WriteByte('}')

if _, err := buf.WriteTo(w); err != nil {
h.Set(errheader, err.Error())
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}

0 comments on commit 55198e8

Please sign in to comment.