-
Notifications
You must be signed in to change notification settings - Fork 0
/
createUser.go
55 lines (48 loc) · 1.29 KB
/
createUser.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
package main
import (
"encoding/json"
"net/http"
"errors"
"github.com/PratikforCoding/chirpy.git/internal/auth"
"github.com/PratikforCoding/chirpy.git/internal/database"
)
type User struct {
ID int `json:"id"`
Email string `json:"email"`
Password string `json:"password"`
}
func(cfg *apiConfig)handlerUsersCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Password string `json:"password"`
Email string `json:"email"`
}
type returnUser struct {
ID int `json:"id"`
Email string `json:"email"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
responseWithError(w, http.StatusInternalServerError, "Error decoding parameter")
return
}
hashedPassword, err := auth.HashedPassword(params.Password)
if err != nil {
responseWithError(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) {
responseWithError(w, http.StatusConflict, "User already exists")
return
}
responseWithError(w, http.StatusInternalServerError, "Couldn't create user")
return
}
responseWithJson(w, http.StatusCreated, returnUser {
Email: user.Email,
ID: user.ID,
})
}