generated from ElnuDev/go-project
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.
55 lines
1.3 KiB
55 lines
1.3 KiB
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) {
|
|
// Remove in production, enables live template reloading
|
|
if file != "" {
|
|
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)
|
|
}
|
|
}
|