Files
learn-file-storage-s3-golan…/handler_users.go
Daniel Hjartland 75be79c6cf initial commit
2025-01-02 16:32:57 +01:00

47 lines
1.2 KiB
Go

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(&params)
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)
}