an updated and hopefully faster version of the ST Toolbox
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

54 lines
1.4 KiB

package web
import (
"bytes"
"html/template"
"net/http"
root "marmic/servicetrade-toolbox"
"marmic/servicetrade-toolbox/internal/api"
"marmic/servicetrade-toolbox/internal/middleware"
"github.com/gorilla/csrf"
)
func GenericHandler(w http.ResponseWriter, r *http.Request) {
session, ok := r.Context().Value(middleware.SessionKey).(*api.Session)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tmpl := root.WebTemplates
var csrfCookie string
if c, err := r.Cookie("XSRF-TOKEN"); err == nil {
csrfCookie = c.Value
} else if c, err := r.Cookie("XSRF-TOKEN-VALUE"); err == nil {
csrfCookie = c.Value
}
data := map[string]interface{}{
"Title": "Generic",
"Session": session,
"CSRFField": csrf.TemplateField(r),
"CSRFToken": csrf.Token(r),
"CSRFCookie": csrfCookie,
}
if r.Header.Get("HX-Request") == "true" {
if err := tmpl.ExecuteTemplate(w, "generic_content", data); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
return
}
var contentBuf bytes.Buffer
if err := tmpl.ExecuteTemplate(&contentBuf, "generic_content", data); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
data["BodyContent"] = template.HTML(contentBuf.String())
if err := tmpl.ExecuteTemplate(w, "layout.html", data); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}