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:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user