refactor: extract API handlers into internal packages

Move HTTP handler logic out of main into internal api and server packages,
slimming main to a thin entrypoint. Bundles bug fixes: login nil-panic,
empty-password validation, chirp sort ordering, duplicate-email 409, and
restricting the file server to the assets directory.
This commit is contained in:
Stevan Freeborn
2026-08-15 22:07:00 -05:00
parent aaa913ccab
commit cf79c8a626
12 changed files with 966 additions and 817 deletions
+74
View File
@@ -0,0 +1,74 @@
package server
import (
"fmt"
"net/http"
"github.com/StevanFreeborn/chirpy/internal/api"
)
// handleFiles serves static assets and counts requests for the metrics page.
func (s *Server) handleFiles(prefix string) http.Handler {
fileServer := http.StripPrefix(prefix, http.FileServer(http.Dir("./assets")))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.fileServerHits.Add(1)
fileServer.ServeHTTP(w, r)
})
}
// HandleIndex serves the static landing page and counts the visit.
func (s *Server) HandleIndex(w http.ResponseWriter, r *http.Request) {
s.fileServerHits.Add(1)
w.Header().Add("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(s.indexHTML)
}
// HandleHealthChecks reports that the service is up.
func (s *Server) HandleHealthChecks(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
// HandleReset clears the file server hit counter and deletes all users. It is
// only available when the platform is "dev".
func (s *Server) HandleReset(w http.ResponseWriter, r *http.Request) {
if s.platform != "dev" {
w.WriteHeader(http.StatusForbidden)
return
}
s.fileServerHits.Store(0)
if err := s.db.DeleteAllUsers(r.Context()); err != nil {
api.WriteError(w, http.StatusInternalServerError, "Failed to reset database")
return
}
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
// HandleMetrics renders the admin page showing how many times the file server
// has been hit.
func (s *Server) HandleMetrics(w http.ResponseWriter, r *http.Request) {
hits := s.fileServerHits.Load()
w.Header().Add("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
template := `
<html>
<body>
<h1>Welcome, Chirpy Admin</h1>
<p>Chirpy has been visited %d times!</p>
</body>
</html>
`
fmt.Fprintf(w, template, hits)
}
+205
View File
@@ -0,0 +1,205 @@
package server
import (
"fmt"
"net/http"
"slices"
"strings"
"time"
"github.com/StevanFreeborn/chirpy/internal/api"
"github.com/StevanFreeborn/chirpy/internal/auth"
"github.com/StevanFreeborn/chirpy/internal/database"
"github.com/google/uuid"
)
const (
ascending = "asc"
descending = "desc"
)
type createChirpRequest struct {
Body string `json:"body"`
UserId string `json:"user_id"`
}
type chirpResponse struct {
Id string `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Body string `json:"body"`
UserId string `json:"user_id"`
}
// toChirpResponse maps a database Chirp to its API response shape.
func toChirpResponse(c database.Chirp) chirpResponse {
return chirpResponse{
Id: c.ID.String(),
CreatedAt: c.CreatedAt.Format(time.RFC3339),
UpdatedAt: c.UpdatedAt.Format(time.RFC3339),
Body: c.Body,
UserId: c.UserID.String(),
}
}
// HandleCreateChirp creates a chirp for the authenticated user.
func (s *Server) HandleCreateChirp(w http.ResponseWriter, r *http.Request) {
bearerToken, err := auth.GetBearerToken(r.Header)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
requestUserId, err := auth.ValidateJWT(bearerToken, s.jwtSecret)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
createChirpRequest, err := api.DecodeJSON[createChirpRequest](r)
if err != nil {
api.WriteError(w, http.StatusBadRequest, err.Error())
return
}
if len(createChirpRequest.Body) > 140 {
api.WriteError(w, http.StatusBadRequest, "Chirp is too long")
return
}
createChirpParams := database.CreateChirpParams{
Body: cleanProfanity(createChirpRequest.Body),
UserID: requestUserId,
}
createdChirp, err := s.db.CreateChirp(r.Context(), createChirpParams)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Failed to create chirp. 🤷🏻‍♂️")
return
}
api.WriteJSON(w, http.StatusCreated, toChirpResponse(createdChirp))
}
// HandleGetChirps lists chirps, optionally filtered by author_id and sorted by
// the sort query parameter.
func (s *Server) HandleGetChirps(w http.ResponseWriter, r *http.Request) {
authorId := r.URL.Query().Get("author_id")
sortDir := r.URL.Query().Get("sort")
hasAuthorId := strings.TrimSpace(authorId) != ""
hasSort := strings.TrimSpace(sortDir) != ""
validAuthorId, err := uuid.Parse(authorId)
if hasAuthorId && err != nil {
api.WriteError(w, http.StatusBadRequest, "Author id must be a valid uuid")
return
}
if hasSort && sortDir != ascending && sortDir != descending {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("Sort direction must be either '%s' or '%s'", ascending, descending))
return
}
if !hasSort {
sortDir = ascending
}
var existingChirps []database.Chirp
if hasAuthorId {
existingChirps, err = s.db.GetChirpsByAuthor(r.Context(), validAuthorId)
} else {
existingChirps, err = s.db.GetAllChirps(r.Context())
}
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Unable to retrieve chirps")
return
}
slices.SortFunc(existingChirps, func(a, b database.Chirp) int {
if sortDir == descending {
return b.CreatedAt.Compare(a.CreatedAt)
}
return a.CreatedAt.Compare(b.CreatedAt)
})
chirps := make([]chirpResponse, 0, len(existingChirps))
for _, c := range existingChirps {
chirps = append(chirps, toChirpResponse(c))
}
api.WriteJSON(w, http.StatusOK, chirps)
}
// HandleGetChirp returns a single chirp by id.
func (s *Server) HandleGetChirp(w http.ResponseWriter, r *http.Request) {
chirpId := r.PathValue("id")
validChirpId, err := uuid.Parse(chirpId)
if err != nil {
api.WriteError(w, http.StatusBadRequest, "Chirp id is not valid. id must be valid UUID.")
return
}
existingChirp, err := s.db.GetChirpById(r.Context(), validChirpId)
if err != nil {
api.WriteError(w, http.StatusNotFound, "No chirp with given id found.")
return
}
api.WriteJSON(w, http.StatusOK, toChirpResponse(existingChirp))
}
// HandleDeleteChirp deletes a chirp owned by the authenticated user.
func (s *Server) HandleDeleteChirp(w http.ResponseWriter, r *http.Request) {
accessToken, err := auth.GetBearerToken(r.Header)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
requestUserId, err := auth.ValidateJWT(accessToken, s.jwtSecret)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
chirpId := r.PathValue("id")
validChirpId, err := uuid.Parse(chirpId)
if err != nil {
api.WriteError(w, http.StatusBadRequest, "Chirp id must be a valid uuid for an existing chirp")
return
}
existingChirp, err := s.db.GetChirpById(r.Context(), validChirpId)
if err != nil {
api.WriteError(w, http.StatusNotFound, "Chirp id must be a valid uuid for an existing chirp")
return
}
if existingChirp.UserID != requestUserId {
api.WriteError(w, http.StatusForbidden, "You can not delete a chirp that does not belong to you")
return
}
if err := s.db.DeleteChirpById(r.Context(), existingChirp.ID); err != nil {
api.WriteError(w, http.StatusInternalServerError, "Unable to delete chirp")
return
}
api.WriteJSON(w, http.StatusNoContent, nil)
}
+307
View File
@@ -0,0 +1,307 @@
package server
import (
"database/sql"
"errors"
"net/http"
"strings"
"time"
"github.com/StevanFreeborn/chirpy/internal/api"
"github.com/StevanFreeborn/chirpy/internal/auth"
"github.com/StevanFreeborn/chirpy/internal/database"
"github.com/lib/pq"
)
const accessTokenTTL = time.Hour
type createUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
type userResponse struct {
Id string `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Email string `json:"email"`
IsChirpyRed bool `json:"is_chirpy_red"`
}
// toUserResponse maps a database User to its API response shape.
func toUserResponse(u database.User) userResponse {
return userResponse{
Id: u.ID.String(),
CreatedAt: u.CreatedAt.Format(time.RFC3339),
UpdatedAt: u.UpdatedAt.Format(time.RFC3339),
Email: u.Email,
IsChirpyRed: u.IsChirpyRed,
}
}
// HandleCreateUser registers a new user and returns it.
func (s *Server) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
createUserRequest, err := api.DecodeJSON[createUserRequest](r)
if err != nil {
api.WriteError(w, http.StatusBadRequest, err.Error())
return
}
trimmedEmail := strings.TrimSpace(createUserRequest.Email)
if trimmedEmail == "" {
api.WriteError(w, http.StatusBadRequest, "email is required. must be valid email address.")
return
}
trimmedPassword := strings.TrimSpace(createUserRequest.Password)
if trimmedPassword == "" {
api.WriteError(w, http.StatusBadRequest, "password is required. must be non-empty string.")
return
}
hashedPassword, err := auth.HashPassword(trimmedPassword)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Uh oh we were unable to create a new user")
return
}
createUserParams := database.CreateUserParams{
Email: trimmedEmail,
HashedPassword: hashedPassword,
}
createdUser, err := s.db.CreateUser(r.Context(), createUserParams)
if err != nil {
var pgErr *pq.Error
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
api.WriteError(w, http.StatusConflict, "A user with that email already exists")
return
}
api.WriteError(w, http.StatusInternalServerError, "Uh oh we were unable to create a new user")
return
}
api.WriteJSON(w, http.StatusCreated, toUserResponse(createdUser))
}
type loginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
func (r *loginRequest) Validate() error {
if strings.TrimSpace(r.Email) == "" || strings.TrimSpace(r.Password) == "" {
return api.NewError("Email and password must be non-empty string")
}
return nil
}
type loginResponse struct {
Id string `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Email string `json:"email"`
IsChirpyRed bool `json:"is_chirpy_red"`
Token string `json:"token"`
RefreshToken string `json:"refresh_token"`
}
// HandleLogin authenticates a user and returns new access and refresh tokens.
func (s *Server) HandleLogin(w http.ResponseWriter, r *http.Request) {
loginRequest, err := api.DecodeJSON[loginRequest](r)
if err != nil {
api.WriteError(w, http.StatusBadRequest, err.Error())
return
}
if err := loginRequest.Validate(); err != nil {
api.WriteError(w, http.StatusBadRequest, err.Error())
return
}
existingUser, err := s.db.GetUserByEmail(r.Context(), loginRequest.Email)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "Invalid login request")
return
}
isCorrectPassword, err := auth.CheckPasswordHash(loginRequest.Password, existingUser.HashedPassword)
if err != nil || !isCorrectPassword {
api.WriteError(w, http.StatusUnauthorized, "Invalid login request")
return
}
accessToken, err := auth.MakeJWT(existingUser.ID, s.jwtSecret, accessTokenTTL)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Login failed")
return
}
createRefreshTokenParams := database.CreateRefreshTokenParams{
Token: auth.MakeRefreshToken(),
ExpiresAt: time.Now().Add(60 * 24 * time.Hour),
RevokedAt: sql.NullTime{
Valid: false,
},
UserID: existingUser.ID,
}
createdRefreshToken, err := s.db.CreateRefreshToken(r.Context(), createRefreshTokenParams)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Login failed")
return
}
user := toUserResponse(existingUser)
api.WriteJSON(w, http.StatusOK, loginResponse{
Id: user.Id,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
IsChirpyRed: user.IsChirpyRed,
Token: accessToken,
RefreshToken: createdRefreshToken.Token,
})
}
type refreshTokenResponse struct {
Token string `json:"token"`
}
// HandleRefresh exchanges a valid, unrevoked refresh token for a new access
// token.
func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
refreshToken, err := auth.GetBearerToken(r.Header)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "Unable to refresh token")
return
}
existingRefreshToken, err := s.db.GetRefreshTokenByToken(r.Context(), refreshToken)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "Unable to refresh token")
return
}
if existingRefreshToken.ExpiresAt.Before(time.Now()) || existingRefreshToken.RevokedAt.Valid {
api.WriteError(w, http.StatusUnauthorized, "Unable to refresh token")
return
}
accessToken, err := auth.MakeJWT(existingRefreshToken.UserID, s.jwtSecret, accessTokenTTL)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Failed to refresh token")
return
}
// TODO: We should rotate the refresh token
api.WriteJSON(w, http.StatusOK, refreshTokenResponse{
Token: accessToken,
})
}
// HandleRevoke revokes a refresh token so it can no longer be used.
func (s *Server) HandleRevoke(w http.ResponseWriter, r *http.Request) {
refreshToken, err := auth.GetBearerToken(r.Header)
if err != nil {
api.WriteError(w, http.StatusBadRequest, "No refresh token present in request")
return
}
existingRefreshToken, err := s.db.GetRefreshTokenByToken(r.Context(), refreshToken)
if err != nil {
api.WriteError(w, http.StatusNotFound, "Unable to revoke token")
return
}
if err := s.db.RevokeRefreshToken(r.Context(), existingRefreshToken.Token); err != nil {
api.WriteError(w, http.StatusInternalServerError, "Unable to revoke token")
return
}
api.WriteJSON(w, http.StatusNoContent, nil)
}
type updateUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
func (r *updateUserRequest) Validate() error {
if strings.TrimSpace(r.Email) == "" || strings.TrimSpace(r.Password) == "" {
return api.NewError("Email and password must be non-empty string")
}
return nil
}
// HandleUpdateUser updates the authenticated user's email and password.
func (s *Server) HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
accessToken, err := auth.GetBearerToken(r.Header)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
requestUserId, err := auth.ValidateJWT(accessToken, s.jwtSecret)
if err != nil {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
updateUserRequest, err := api.DecodeJSON[updateUserRequest](r)
if err != nil {
api.WriteError(w, http.StatusBadRequest, err.Error())
return
}
if err := updateUserRequest.Validate(); err != nil {
api.WriteError(w, http.StatusBadRequest, err.Error())
return
}
updatedHashedPassword, err := auth.HashPassword(updateUserRequest.Password)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Unable to perform update")
return
}
updateUserParams := database.UpdateUserParams{
ID: requestUserId,
Email: updateUserRequest.Email,
HashedPassword: updatedHashedPassword,
}
updatedUser, err := s.db.UpdateUser(r.Context(), updateUserParams)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Unable to perform update")
return
}
api.WriteJSON(w, http.StatusOK, toUserResponse(updatedUser))
}
+89
View File
@@ -0,0 +1,89 @@
package server
import (
"encoding/json"
"net/http"
"github.com/StevanFreeborn/chirpy/internal/api"
"github.com/StevanFreeborn/chirpy/internal/auth"
"github.com/google/uuid"
)
type userUpgradeData struct {
UserId string `json:"user_id"`
}
type webhookEvent struct {
Event string `json:"event"`
Data any `json:"-"`
}
// UnmarshalJSON captures the raw event data so it can be decoded into the
// concrete type for the event name.
func (p *webhookEvent) UnmarshalJSON(b []byte) error {
type Alias webhookEvent
aux := &struct {
*Alias
RawData json.RawMessage `json:"data"`
}{
Alias: (*Alias)(p),
}
if err := json.Unmarshal(b, aux); err != nil {
return err
}
switch p.Event {
case "user.upgraded":
var data userUpgradeData
if err := json.Unmarshal(aux.RawData, &data); err != nil {
return err
}
p.Data = data
default:
}
return nil
}
// HandleWebhooks processes Polka webhook events, e.g. upgrading a user to
// Chirpy Red.
func (s *Server) HandleWebhooks(w http.ResponseWriter, r *http.Request) {
apiKey, err := auth.GetAPIKey(r.Header)
if err != nil || apiKey != s.polkaKey {
api.WriteError(w, http.StatusUnauthorized, "You are not authorized to perform this action")
return
}
event, err := api.DecodeJSON[webhookEvent](r)
if err != nil {
api.WriteError(w, http.StatusInternalServerError, "Unable to deserialize webhook event")
return
}
switch v := event.Data.(type) {
case userUpgradeData:
validUserId, err := uuid.Parse(v.UserId)
if err != nil {
api.WriteError(w, http.StatusNotFound, "Unable to upgrade user")
return
}
_, err = s.db.UpgradeUser(r.Context(), validUserId)
if err != nil {
api.WriteError(w, http.StatusNotFound, "Unable to upgrade user")
return
}
api.WriteJSON(w, http.StatusNoContent, nil)
default:
api.WriteJSON(w, http.StatusNoContent, nil)
}
}
+22
View File
@@ -0,0 +1,22 @@
package server
import (
"slices"
"strings"
)
var profaneWords = []string{"kerfuffle", "sharbert", "fornax"}
// cleanProfanity replaces profane words with asterisks, case-insensitively,
// matching on whole words only.
func cleanProfanity(body string) string {
words := strings.Split(body, " ")
for i, word := range words {
if slices.Contains(profaneWords, strings.ToLower(word)) {
words[i] = "****"
}
}
return strings.Join(words, " ")
}
+47
View File
@@ -0,0 +1,47 @@
package server
import "testing"
func TestCleanProfanity(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "no profanity",
input: "hello world",
expected: "hello world",
},
{
name: "case insensitive",
input: "That was a KERFUFFLE",
expected: "That was a ****",
},
{
name: "not a substring match",
input: "kerfuffling away",
expected: "kerfuffling away",
},
{
name: "multiple words",
input: "sharbert fornax",
expected: "**** ****",
},
{
name: "empty body",
input: "",
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := cleanProfanity(tt.input)
if got != tt.expected {
t.Errorf("cleanProfanity(%q) = %q, want %q", tt.input, got, tt.expected)
}
})
}
}
+56
View File
@@ -0,0 +1,56 @@
// Package server contains the HTTP handlers for the Chirpy API.
package server
import (
"net/http"
"sync/atomic"
"github.com/StevanFreeborn/chirpy/internal/database"
)
// Server holds the dependencies shared by all HTTP handlers.
type Server struct {
fileServerHits atomic.Int32
db *database.Queries
platform string
jwtSecret []byte
polkaKey string
indexHTML []byte
}
// New creates a Server with its dependencies wired in.
func New(db *database.Queries, platform string, jwtSecret []byte, polkaKey string, indexHTML []byte) *Server {
return &Server{
db: db,
platform: platform,
jwtSecret: jwtSecret,
polkaKey: polkaKey,
indexHTML: indexHTML,
}
}
// Handler returns the fully configured HTTP handler for the application.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /app/assets/", s.handleFiles("/app/assets/"))
mux.HandleFunc("GET /app/{$}", s.HandleIndex)
mux.HandleFunc("GET /admin/metrics", s.HandleMetrics)
mux.HandleFunc("POST /admin/reset", s.HandleReset)
mux.HandleFunc("GET /api/healthz", s.HandleHealthChecks)
mux.HandleFunc("POST /api/login", s.HandleLogin)
mux.HandleFunc("POST /api/refresh", s.HandleRefresh)
mux.HandleFunc("POST /api/revoke", s.HandleRevoke)
mux.HandleFunc("POST /api/users", s.HandleCreateUser)
mux.HandleFunc("PUT /api/users", s.HandleUpdateUser)
mux.HandleFunc("POST /api/polka/webhooks", s.HandleWebhooks)
mux.HandleFunc("GET /api/chirps", s.HandleGetChirps)
mux.HandleFunc("GET /api/chirps/{id}", s.HandleGetChirp)
mux.HandleFunc("POST /api/chirps", s.HandleCreateChirp)
mux.HandleFunc("DELETE /api/chirps/{id}", s.HandleDeleteChirp)
return mux
}