Update template
This commit is contained in:
34
internal/handlers/root.go
Normal file
34
internal/handlers/root.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.clustercockpit.org/moebiusband/go-http-skeleton/web"
|
||||
)
|
||||
|
||||
type PageData struct {
|
||||
Title string
|
||||
}
|
||||
|
||||
func RootHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
file, err := web.Templates.ReadFile("templates/index.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
slog.Error("Error reading template", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
tmpl := template.Must(template.New("index.html").Parse(string(file)))
|
||||
|
||||
data := PageData{
|
||||
Title: "Home",
|
||||
}
|
||||
if err := tmpl.Execute(w, data); err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
slog.Error("Error executing template", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
28
internal/middleware/middleware.go
Normal file
28
internal/middleware/middleware.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Middleware is a function that wraps an http.Handler with custom logic.
|
||||
type Middleware func(http.Handler) http.Handler
|
||||
|
||||
// Chain is a helper to build up a pipeline of middlewares, then apply them to a
|
||||
// final handler.
|
||||
type Chain struct {
|
||||
middlewares []Middleware
|
||||
}
|
||||
|
||||
// Use appends a middleware to the chain.
|
||||
func (c *Chain) Use(m Middleware) {
|
||||
c.middlewares = append(c.middlewares, m)
|
||||
}
|
||||
|
||||
// Then applies the entire chain of middlewares to the final handler in reverse
|
||||
// order.
|
||||
func (c *Chain) Then(h http.Handler) http.Handler {
|
||||
for i := len(c.middlewares) - 1; i >= 0; i-- {
|
||||
h = c.middlewares[i](h)
|
||||
}
|
||||
return h
|
||||
}
|
18
internal/middleware/recover.go
Normal file
18
internal/middleware/recover.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func RecoverMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
slog.Error("Recovered from panic", "error", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user