-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_user.go
More file actions
58 lines (49 loc) · 1.37 KB
/
Copy pathcreate_user.go
File metadata and controls
58 lines (49 loc) · 1.37 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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/google/uuid"
"github.com/nk-reddy/chirpy/internal/auth"
"github.com/nk-reddy/chirpy/internal/database"
)
type userResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
ChirpyRed bool `json:"is_chirpy_red"`
}
type userRequest struct {
Password string `json:"password"`
Email string `json:"email"`
}
func (cfg *apiConfig) handlerCreateUser(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
params := userRequest{}
if err := decoder.Decode(¶ms); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
user, err := cfg.db.CreateUser(r.Context(), database.CreateUserParams{
Email: params.Email,
HashedPassword: hashedPassword,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Add("Content-Type", "application/json; charset=utf-8")
respondWithJSON(w, http.StatusCreated, userResponse{
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
ChirpyRed: false,
})
}