-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathhandler_users.go
46 lines (38 loc) · 1.18 KB
/
handler_users.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
package main
import (
"encoding/json"
"net/http"
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth"
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/database"
)
func (cfg *apiConfig) handlerUsersCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Password string `json:"password"`
Email string `json:"email"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
return
}
if params.Password == "" || params.Email == "" {
respondWithError(w, http.StatusBadRequest, "Email and password are required", nil)
return
}
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't hash password", err)
return
}
user, err := cfg.db.CreateUser(database.CreateUserParams{
Email: params.Email,
Password: hashedPassword,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create user", err)
return
}
respondWithJSON(w, http.StatusCreated, user)
}