diff --git a/controllers/user-controller.go b/controllers/user-controller.go index 38e1209..990116d 100644 --- a/controllers/user-controller.go +++ b/controllers/user-controller.go @@ -25,7 +25,7 @@ func (c *UserController) getUsers(w http.ResponseWriter, r *http.Request) { return } - // TODO: Only admin can do this? + // TODO: Only admin should be allowed to do this? users, err := c.users.List(r.Context()) if err != nil { @@ -33,7 +33,7 @@ func (c *UserController) getUsers(w http.ResponseWriter, r *http.Request) { return } - respond.JSON(w, 200, users) + respond.Data(w, users) } // getUser (`GET /:id`): Get user by id @@ -44,7 +44,7 @@ func (c *UserController) getUser(w http.ResponseWriter, r *http.Request) { return } - // TODO: Only admin can do this? + // TODO: Only admin should be allowed to do this? var user models.User @@ -63,7 +63,7 @@ func (c *UserController) getUser(w http.ResponseWriter, r *http.Request) { } } - respond.JSON(w, 200, user) + respond.Data(w, user) } // login (`POST /login`): Log in as user @@ -106,7 +106,7 @@ func (c *UserController) login(w http.ResponseWriter, r *http.Request) { log.Printf("User %s logged in", user.Name) - respond.JSON(w, 200, user) + respond.Data(w, user) } func (c *UserController) register(w http.ResponseWriter, r *http.Request) { @@ -144,7 +144,7 @@ func (c *UserController) register(w http.ResponseWriter, r *http.Request) { log.Printf("User %s registered", user.Name) - respond.JSON(w, 200, user) + respond.Data(w, user) } // login (`POST /logout`): Log in as user @@ -189,7 +189,7 @@ func (c *UserController) logout(w http.ResponseWriter, r *http.Request) { log.Printf("User %s logged out (clearAll: %t)", user.Name, logoutData.ClearAll) - respond.JSON(w, 200, logoutData) + respond.Data(w, logoutData) } // Mount mounts the controller diff --git a/internal/respond/data.go b/internal/respond/data.go new file mode 100644 index 0000000..7b4a813 --- /dev/null +++ b/internal/respond/data.go @@ -0,0 +1,12 @@ +package respond + +import "net/http" + +// Data responds with a standardized-ish data response object. +func Data(w http.ResponseWriter, data interface{}) { + type dataBody struct { + Data interface{} `json:"data"` + } + + JSON(w, 200, &dataBody{Data: data}) +} diff --git a/internal/respond/error.go b/internal/respond/error.go index 82dd829..6becd78 100644 --- a/internal/respond/error.go +++ b/internal/respond/error.go @@ -10,9 +10,15 @@ func Error(w http.ResponseWriter, code int, kind string, message string) { Message string `json:"message"` } - JSON(w, code, &errorContent{ - Code: code, - Kind: kind, - Message: message, + type errorBody struct { + Error errorContent `json:"error"` + } + + JSON(w, code, &errorBody{ + Error: errorContent{ + Code: code, + Kind: kind, + Message: message, + }, }) }