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