Skip to content

Commit

Permalink
feat: add encode/decode helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
j0lvera committed Dec 24, 2024
1 parent 23e33ee commit 2c6119d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ create table users

created_at timestamptz not null default current_timestamp,
updated_at timestamptz not null default current_timestamp,
email text not null check (char_length(email) < 255) unique,

email text not null check (char_length(email) < 255),
-- bcrypt hash is always 60
password text not null check (char_length(password) = 60),

Expand Down
27 changes: 15 additions & 12 deletions internal/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,28 +26,31 @@ func (s *Server) HandleHealthCheck(w http.ResponseWriter, r *http.Request) {
}

func (s *Server) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string `json:"email"`
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// Decode the request body into a CreateUserParams struct
userParams, err := decode[db.CreateUserParams](r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// TODO:
// - validate the request body and use proper status codes, e.g., malformed request body, etc.
// - hash the password

params := db.CreateUserParams(req)
user, err := s.client.Queries.CreateUser(r.Context(), params)
// Create the user
user, err := s.client.Queries.CreateUser(r.Context(), userParams)
if err != nil {
// Return an unknown error
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.WriteHeader(http.StatusCreated)
err = json.NewEncoder(w).Encode(user)
// We use a custom response so we don't leak the password hash
res := struct {
Id int64 `json:"id"`
msg string
}{
Id: user.ID,
msg: "User created successfully",
}

err = encode(w, r, http.StatusCreated, res)
if err != nil {
return
}
Expand Down
28 changes: 28 additions & 0 deletions internal/server/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package server

import (
"encoding/json"
"fmt"
"net/http"
)

func encode[T any](w http.ResponseWriter, r *http.Request, status int, v T) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)

if err := json.NewEncoder(w).Encode(v); err != nil {
return fmt.Errorf("encode json: %w", err)
}

return nil
}

func decode[T any](r *http.Request) (T, error) {
var v T

if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
return v, fmt.Errorf("decode json: %w", err)
}

return v, nil
}

0 comments on commit 2c6119d

Please sign in to comment.