summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--internal/server/middleware.go24
-rw-r--r--internal/server/server.go27
2 files changed, 40 insertions, 11 deletions
diff --git a/internal/server/middleware.go b/internal/server/middleware.go
new file mode 100644
index 0000000..fe51224
--- /dev/null
+++ b/internal/server/middleware.go
@@ -0,0 +1,24 @@
+package server
+
+import (
+ "log"
+ "net/http"
+)
+
+type statusRecorder struct {
+ http.ResponseWriter
+ status int
+}
+
+func (r *statusRecorder) WriteHeader(code int) {
+ r.ResponseWriter.WriteHeader(code)
+ r.status = code
+}
+
+func logRequests(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
+ next.ServeHTTP(recorder, r)
+ log.Printf("[%s] %s - %s: %d", r.Method, r.RequestURI, r.RemoteAddr, recorder.status)
+ })
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index c391ab3..6de45ca 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -20,15 +20,8 @@ type Server struct {
mux *http.ServeMux
}
-func New(config *Config) *Server {
- tmpl := template.Must(template.ParseFS(web.Files, "templates/*.html"))
- mux := http.NewServeMux()
- return &Server{config, tmpl, mux}
-}
-
-func (s *Server) Serve(addr string) error {
- s.mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
- log.Printf("[%s] %s - %s", r.Method, r.RequestURI, r.RemoteAddr)
+func (s *Server) routes() {
+ s.mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
err := s.tmpl.ExecuteTemplate(w, "index.html", nil)
if err != nil {
@@ -36,10 +29,12 @@ func (s *Server) Serve(addr string) error {
return
}
})
+}
- httpSrv := http.Server{
+func (s *Server) Serve(addr string) error {
+ httpSrv := &http.Server{
Addr: addr,
- Handler: s.mux,
+ Handler: logRequests(s.mux),
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
@@ -47,3 +42,13 @@ func (s *Server) Serve(addr string) error {
log.Printf("Server \"%s\" listening at %s", s.config.Name, addr)
return httpSrv.ListenAndServe()
}
+
+func New(c *Config) *Server {
+ s := &Server{
+ config: c,
+ mux: http.NewServeMux(),
+ tmpl: template.Must(template.ParseFS(web.Files, "templates/*.html")),
+ }
+ s.routes()
+ return s
+}