Sender is a GO library for create a HTTP JSON response using http.ResponseWriter as writer output.
- Send a JSON response error with a simple description error.
- Send a JSON response error with a custom field error.
- Send a JSON response error with a list of custom fields errors.
- Send a JSON response object.
Standard go get
:
$ go get github.com/mig-elgt/sender
func WithErrorHandle(w http.ResponseWriter, r *http.Request) {
sender.
NewJSON(w, http.StatusInternalServerError).
WithError(codes.Internal, "Something went wrong..").
Send()
}
// Output
// {
// "error": {
// "status": 500,
// "error": "INTERNAL",
// "description": "Something went wrong..."
// }
// }
func WithFieldErrorHandle(w http.ResponseWriter, r *http.Request) {
sender.
NewJSON(w, http.StatusBadRequest).
WithFieldError(
codes.InvalidArgument,
"user_id",
"User ID is required",
).
Send()
}
// Output
// {
// "error": {
// "status": 400,
// "error": "INVALID_ARGUMENT",
// "description": "One or more fields raised validation errors.",
// "fields": {
// "user_id": "User ID is required"
// }
// }
// }
func WithFieldsErrorHandle(w http.ResponseWriter, r *http.Request) {
sender.
NewJSON(w, http.StatusBadRequest).
WithFieldsError(
codes.InvalidArgument,
map[string]string{
"user_id": "User ID is required",
"email": "Email has invalid format",
},
).
Send()
}
// Output
// {
// "error": {
// "status": 400,
// "error": "INVALID_ARGUMENT",
// "description": "One or more fields raised validation errors.",
// "fields": {
// "email": "Email has invalid format",
// "user_id": "User ID is required"
// }
// }
// }
func Handle(w http.ResponseWriter, r *http.Request) {
type response struct {
Status int `json:"status"`
ID int `json:"id"`
}
sender.
NewJSON(w, http.StatusOk).
Send(&response{
Status: 200,
ID: 100,
})
}
// Output
// {
// "status": 200,
// "id": 100,
// }