/
handlers_users.go
49 lines (39 loc) · 1.08 KB
/
handlers_users.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package http
import (
"encoding/json"
"net/http"
"github.com/bnkamalesh/errors"
"github.com/bnkamalesh/webgo/v6"
"github.com/bnkamalesh/goapp/internal/users"
)
// CreateUser is the HTTP handler to create a new user
// This handler does not use any framework, instead just the standard library
func (h *Handlers) CreateUser(w http.ResponseWriter, r *http.Request) error {
u := new(users.User)
err := json.NewDecoder(r.Body).Decode(u)
if err != nil {
return errors.InputBodyErr(err, "invalid JSON provided")
}
createdUser, err := h.api.CreateUser(r.Context(), u)
if err != nil {
return err
}
b, err := json.Marshal(createdUser)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(b)
return err
}
// ReadUserByEmail is the HTTP handler to read an existing user by email
func (h *Handlers) ReadUserByEmail(w http.ResponseWriter, r *http.Request) error {
wctx := webgo.Context(r)
email := wctx.Params()["email"]
out, err := h.api.ReadUserByEmail(r.Context(), email)
if err != nil {
return err
}
webgo.R200(w, out)
return nil
}