github.com/xmidt-org/webpa-common@v1.11.9/xhttp/error.go (about) 1 package xhttp 2 3 import ( 4 "fmt" 5 "net/http" 6 ) 7 8 // Error is an HTTP-specific carrier of error information. In addition to implementing error, 9 // this type also implements go-kit's StatusCoder and Headerer. The json.Marshaler interface 10 // is implemented so that the default go-kit error encoder will always emit a JSON message. 11 type Error struct { 12 Code int 13 Header http.Header 14 Text string 15 } 16 17 func (e *Error) StatusCode() int { 18 return e.Code 19 } 20 21 func (e *Error) Headers() http.Header { 22 return e.Header 23 } 24 25 func (e *Error) Error() string { 26 return e.Text 27 } 28 29 func (e *Error) MarshalJSON() ([]byte, error) { 30 return []byte(fmt.Sprintf(`{"code": %d, "text": "%s"}`, e.Code, e.Text)), nil 31 } 32 33 // WriteErrorf provides printf-style functionality for writing out the results of some operation. 34 // The response status code is set to code, and a JSON message of the form {"code": %d, "message": "%s"} is 35 // written as the response body. fmt.Sprintf is used to turn the format and parameters into a single string 36 // for the message. 37 // 38 // Although the typical use case for this function is to return a JSON error, this function can be used 39 // for non-error responses. 40 func WriteErrorf(response http.ResponseWriter, code int, format string, parameters ...interface{}) (int, error) { 41 response.Header().Set("Content-Type", "application/json") 42 response.WriteHeader(code) 43 44 return fmt.Fprintf( 45 response, 46 `{"code": %d, "message": "%s"}`, 47 code, 48 fmt.Sprintf(format, parameters...), 49 ) 50 } 51 52 // WriteError provides print-style functionality for writing a JSON message as a response. No format parameters 53 // are used. The value parameter is subjected to the default stringizing rules of the fmt package. 54 func WriteError(response http.ResponseWriter, code int, value interface{}) (int, error) { 55 response.Header().Set("Content-Type", "application/json") 56 response.WriteHeader(code) 57 58 return fmt.Fprintf( 59 response, 60 `{"code": %d, "message": "%s"}`, 61 code, 62 value, 63 ) 64 }