-
Notifications
You must be signed in to change notification settings - Fork 0
/
createUser.go
52 lines (44 loc) · 1.25 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
package main
import (
"encoding/json"
"golang.org/x/crypto/bcrypt"
"net/http"
"strings"
)
func (cfg *apiConfig) createUserHandler(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Password string `json:"password"`
Email string `json:"email"`
}
type response struct {
ID int `json:"id"`
Email string `json:"email"`
IsChirpyRed bool `json:"is_chirpy_red"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request")
return
}
if !strings.Contains(params.Email, "@") || !strings.Contains(params.Email, ".") {
respondWithError(w, http.StatusBadRequest, "Invalid email")
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(params.Password), bcrypt.DefaultCost)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Internal Server Error")
return
}
user, err := cfg.db.CreateUser(params.Email, hashedPassword)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Internal Server Error")
return
}
respondWithJSON(w, http.StatusCreated, response{
ID: user.ID,
Email: user.Email,
IsChirpyRed: user.IsChirpyRed,
})
}