Rename package srverrors to httperror
- Package names are preferred to be in singular form¹. - Since errors are just for HTTP and not generic, I changed the base name to 'http'. - I didn't name it simply 'error', because it would then conflict with the - standard 'error' interface. ¹: https://rakyll.org/style-packages/
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
package httperror
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// A ServerErrMessage represents the reason why the error happened
|
||||
type ServerErrMessage struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// ErrorJSON writes the provided error as a JSON body to the provided
|
||||
// http.ResponseWriter, after setting the appropriate Content-Type header
|
||||
func ErrorJSON(w http.ResponseWriter, error string, code int) {
|
||||
body, _ := json.Marshal(
|
||||
ServerErrMessage{
|
||||
Reason: error,
|
||||
},
|
||||
)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
Reference in New Issue
Block a user