-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_users_create.go
More file actions
73 lines (54 loc) · 1.49 KB
/
handler_users_create.go
File metadata and controls
73 lines (54 loc) · 1.49 KB
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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/SandeshNarayan/chirpy/internal/auth"
"github.com/SandeshNarayan/chirpy/internal/database"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
IsChirpyRed bool `json:"is_chirpy_red"`
Password string `json:"-"`
}
func (cfg *apiConfig) handlerUsersCreate(w http.ResponseWriter,r *http.Request){
w.Header().Set("Content-Type", "application/json")
type parameter struct {
Password string `json:"password"`
Email string `json:"email"`
}
type response struct{
User
}
params:= parameter{}
if err := json.NewDecoder(r.Body).Decode(¶ms); err!=nil{
respondWithError(w, http.StatusBadRequest, "Couldnt decode parameters", err)
return
}
hashedPassword, err := auth.HashPassword(params.Password)
if err!=nil {
respondWithError(w, http.StatusInternalServerError, "Couldnt hash password", err)
return
}
user, err := cfg.dbQueries.CreateUser(r.Context(), database.CreateUserParams{
HashedPassword: hashedPassword,
Email: params.Email,
})
if err!=nil{
respondWithError(w, http.StatusInternalServerError, "Couldnt create users", err)
return
}
respondWithJson(w, http.StatusCreated, response{
User:User{
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: params.Email,
IsChirpyRed: user.IsChirpyRed,
},
})
}