Creating registerUserHandler and registering the endpoint in our routes.go
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 1m34s

This commit is contained in:
Maxime Delporte
2025-11-25 15:54:43 +01:00
parent 2bd0ae90bc
commit 72503a55ff
2 changed files with 71 additions and 1 deletions

67
cmd/api/users.go Normal file
View File

@@ -0,0 +1,67 @@
package main
import (
"errors"
"net/http"
"greenlight.craftr.fr/internal/data"
"greenlight.craftr.fr/internal/validator"
)
func (app *application) registerUserHandler(w http.ResponseWriter, r *http.Request) {
// Create an anonymous struct to hold the expected data from the request body
var input struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
}
// Parse the request body into the anonymous struct
err := app.readJSON(w, r, &input)
if err != nil {
app.badRequestResponse(w, r, err)
return
}
// Copy the data from the request body into a new User struct. Notice also that we set the Activated field to false, which isn't strictly necessary because the Activated field will have the zero-value of false by default. But setting this explicitly helps to male our intentions clear to anyone reading the code.
user := &data.User{
Name: input.Name,
Email: input.Email,
Activated: false,
}
// Use the Password.Set() method to generate and store the hashed and plaintext passwords
err = user.Password.Set(input.Password)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
v := validator.New()
// Validate the user struct and return the error messages to the client if any of the checks fail
if data.ValidateUser(v, user); !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
// Insert the user data into the database
err = app.models.Users.Insert(user)
if err != nil {
switch {
// If we get a ErrDuplicateEmail error, use the v.AddError() method to manually add a message to the validator instance, and then cal our failedValidationResponse() helper
case errors.Is(err, data.ErrDuplicateEmail):
v.AddError("email", "a user with this email address already exists")
app.failedValidationResponse(w, r, v.Errors)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// Write a JSON response containing the user data along with a 201 Created status code
err = app.writeJSON(w, http.StatusCreated, envelope{"user": user}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}