2026-08-15 22:06:18 -05:00
|
|
|
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)
|
2026-08-15 22:09:59 -05:00
|
|
|
_, _ = w.Write(s.indexHTML)
|
2026-08-15 22:06:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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)
|
2026-08-15 22:09:59 -05:00
|
|
|
_, _ = w.Write([]byte("OK"))
|
2026-08-15 22:06:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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)
|
2026-08-15 22:09:59 -05:00
|
|
|
_, _ = w.Write([]byte("OK"))
|
2026-08-15 22:06:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
|
}
|