github.com/quay/claircore@v1.5.28/pkg/jsonerr/jsonerr.go (about)

     1  package jsonerr
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  )
     7  
     8  type Additional interface{}
     9  
    10  type Response struct {
    11  	Code    string `json:"code"`
    12  	Message string `json:"message"`
    13  	// Additional must be json serializable or expect errors
    14  	Additional `json:"additional,omitempty"`
    15  }
    16  
    17  // JsonError works like http.Error but uses our response
    18  // struct as the body of the response. Like http.Error
    19  // you will still need to call a naked return in the http handler
    20  func Error(w http.ResponseWriter, r *Response, httpcode int) {
    21  	w.Header().Set("Content-Type", "application/json")
    22  	w.Header().Set("X-Content-Type-Options", "nosniff")
    23  	w.WriteHeader(httpcode)
    24  	b, _ := json.Marshal(r)
    25  
    26  	w.Write(b)
    27  }