Skip to content

Commit

Permalink
move map type to json middleware and add E type
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertWHurst committed Jan 10, 2025
1 parent 4ed2c66 commit 2d106ee
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
3 changes: 0 additions & 3 deletions map.go

This file was deleted.

10 changes: 10 additions & 0 deletions middleware/json/body-types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package json

// M is shorthand for a map[string]any. It is provided as a convenience for
// defining JSON objects in a more concise manner.
type M map[string]any

// E is shorthand for Error. If you want to return a JSON wrapped error, you can
// use this type. The JSON response will be {"error": "your error message"}.
// If the status is not set, it will default to 400.
type E string
9 changes: 9 additions & 0 deletions middleware/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ func marshalResponseBody(ctx *navaros.Context) {
if from != nil {
ctx.Headers.Add("Content-Type", "application/json")
}
switch str := from.(type) {
case E:
if ctx.Status == 0 {
ctx.Status = 400
}
from = map[string]string{"error": string(str)}
case string:
from = map[string]string{"message": str}
}
jsonBytes, err := json.Marshal(from)
if err != nil {
return nil, err
Expand Down

0 comments on commit 2d106ee

Please sign in to comment.