-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_handler.go
101 lines (87 loc) · 2.39 KB
/
user_handler.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package server
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/go-chi/chi"
uuid "github.com/satori/go.uuid"
"github.com/francoposa/golang-auth/authentication/domain"
)
type UserHandler struct {
repo domain.UserRepo
}
func NewUserHandler(repo domain.UserRepo) *UserHandler {
return &UserHandler{repo: repo}
}
func (h *UserHandler) Get(w http.ResponseWriter, r *http.Request) {
idStr := chi.URLParam(r, "id")
id, err := uuid.FromString(idStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
retrievedUser, err := h.repo.GetByID(id)
var notFoundErr domain.UserNotFoundError
if errors.As(err, ¬FoundErr) {
w.WriteHeader(http.StatusNotFound)
body := map[string]string{"errorMessage": err.Error()}
json.NewEncoder(w).Encode(body)
return
}
err = json.NewEncoder(w).Encode(
HttpReadUser{
ID: retrievedUser.ID,
Username: retrievedUser.Username,
Email: retrievedUser.Email,
},
)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
}
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
httpUser := HttpCreateUser{}
err := json.NewDecoder(r.Body).Decode(&httpUser)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
err = httpUser.Validate()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
body := map[string]string{"errorMessage": err.Error()}
json.NewEncoder(w).Encode(body)
return
}
user, password, err := domain.NewUser(httpUser.Username, httpUser.Email, httpUser.Password)
var usernameErr domain.UsernameInvalidError
var emailErr domain.EmailInvalidError
var passwordErr domain.PasswordInvalidLengthError
if errors.As(err, &usernameErr) || errors.As(err, &emailErr) || errors.As(err, &passwordErr) {
w.WriteHeader(http.StatusUnprocessableEntity)
body := map[string]string{"errorMessage": err.Error()}
json.NewEncoder(w).Encode(body)
return
}
createdUser, err := h.repo.Create(user, password)
var existsErr domain.UserAlreadyExistsError
if errors.As(err, &existsErr) {
w.WriteHeader(http.StatusConflict)
body := map[string]string{"errorMessage": err.Error()}
json.NewEncoder(w).Encode(body)
return
}
err = json.NewEncoder(w).Encode(
HttpReadUser{
ID: createdUser.ID,
Username: createdUser.Username,
Email: createdUser.Email,
},
)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
}
}