-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle_users_create.go
58 lines (50 loc) · 1.29 KB
/
handle_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
package main
import (
"encoding/json"
"errors"
"net/http"
"github.com/ClemSK/chirpy/internal/auth"
"github.com/ClemSK/chirpy/internal/database"
)
type User struct {
Email string `json:"email"`
ID int `json:"id"`
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, "Could not decode parameter")
return
}
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Could not 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, "Could not create user")
return
}
respondWithJSON(w, http.StatusCreated, response{
User: User{
Email: user.Email,
ID: user.ID,
},
})
}