-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_users_create.go
60 lines (51 loc) · 1.34 KB
/
handler_users_create.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
package main
import (
"encoding/json"
"errors"
"net/http"
"github.com/eliird/chirpy/internal/auth"
"github.com/eliird/chirpy/internal/database"
)
type User struct {
ID int `json:"id"`
Email string `json:"email"`
Password string `json:"-"`
IsChirpyRed bool `json:"is_chirpy_red"`
}
func (cfg *apiConfig) handlerUsersCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Password string `json:"password"`
Email string `json:"email"`
}
type response struct {
User
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't hash password")
return
}
user, err := cfg.DB.CreateUser(params.Email, hashedPassword)
if err != nil {
if errors.Is(err, database.ErrAlreadyExists) {
respondWithError(w, http.StatusConflict, "User already exists")
return
}
respondWithError(w, http.StatusInternalServerError, "Couldn't create user")
return
}
respondWithJSON(w, http.StatusCreated, response{
User: User{
ID: user.ID,
Email: user.Email,
IsChirpyRed: user.IsChirpyRed,
},
})
}