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 := `
Chirpy has been visited %d times!
` fmt.Fprintf(w, template, hits) }