package httputils import ( "fmt" "net/http" "text/template" ) type Handler = func(http.ResponseWriter, *http.Request) func GenerateHandler( file string, handler func(http.ResponseWriter, *http.Request) bool, data func(http.ResponseWriter, *http.Request) any, methods []string, ) Handler { var tmpl *template.Template if file != "" { tmpl = template.Must(template.ParseFiles(fmt.Sprintf("templates/%s", file))) } return func(w http.ResponseWriter, r *http.Request) { tmpl = template.Must(template.ParseFiles(fmt.Sprintf("templates/%s", file))) for _, method := range methods { if method == r.Method { goto ok } } w.WriteHeader(http.StatusMethodNotAllowed) return ok: renderTemplate := handler(w, r) if renderTemplate && tmpl != nil { w.Header().Set("Content-Type", "text/html; charset=utf-8") tmpl.Execute(w, data(w, r)) } } } func GenerateSseHandler(handler Handler) Handler { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) return } w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") w.WriteHeader(http.StatusOK) handler(w, r) } }