refactor: add logs and cache removar to middleware
This commit is contained in:
33
internals/middleware.go
Normal file
33
internals/middleware.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package internals
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Middleware struct {
|
||||
handler http.Handler
|
||||
dev bool
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
m.logger.Printf("Handling request. path=%s", r.URL.Path)
|
||||
|
||||
if m.dev {
|
||||
r.URL.Scheme = "http"
|
||||
} else {
|
||||
r.URL.Scheme = "https"
|
||||
}
|
||||
|
||||
m.handler.ServeHTTP(w, r)
|
||||
|
||||
if m.dev {
|
||||
w.Header().Del("Cache-Control")
|
||||
w.Header().Add("Cache-Control", "max-age=0")
|
||||
}
|
||||
}
|
||||
|
||||
func NewMiddleware(handler http.Handler, dev bool, logger *log.Logger) *Middleware {
|
||||
return &Middleware{handler, dev, logger}
|
||||
}
|
||||
16
main.go
16
main.go
@@ -36,12 +36,6 @@ func main() {
|
||||
logger.Printf("Registering page route. page=%s route=%s", route.Path, path)
|
||||
|
||||
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
logger.Printf("Handling request. path=%s", r.URL.Path)
|
||||
|
||||
if *dev {
|
||||
w.Header().Add("Cache-Control", "max-age=0")
|
||||
}
|
||||
|
||||
w.Header().Add("Content-Type", "text/html")
|
||||
|
||||
err := route.Component.Render(r.Context(), w)
|
||||
@@ -51,18 +45,12 @@ func main() {
|
||||
})
|
||||
}
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if *dev {
|
||||
w.Header().Add("Cache-Control", "max-age=0")
|
||||
}
|
||||
|
||||
if r.URL.Path != "/" {
|
||||
logger.Printf("Handling file server request. path=%s", r.URL.Path)
|
||||
http.FileServer(http.Dir(*staticDir)).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Printf("Handling request. path=%s", r.URL.Path)
|
||||
|
||||
w.Header().Add("Content-Type", "text/html")
|
||||
|
||||
index := slices.IndexFunc(config.ROUTES, func(route internals.Page) bool {
|
||||
@@ -77,7 +65,9 @@ func main() {
|
||||
})
|
||||
|
||||
logger.Printf("Running server at port: %v", *port)
|
||||
err := http.ListenAndServe(fmt.Sprintf(":%v", *port), mux)
|
||||
|
||||
middleware := internals.NewMiddleware(mux, *dev, log.Default())
|
||||
err := http.ListenAndServe(fmt.Sprintf(":%v", *port), middleware)
|
||||
if err != nil {
|
||||
logger.Fatalf("Server crashed due to:\n%s", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user