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.
51 lines
1.1 KiB
51 lines
1.1 KiB
2 years ago
|
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),
|
||
|
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) {
|
||
|
for _, method := range methods {
|
||
|
if method == r.Method {
|
||
|
goto ok
|
||
|
}
|
||
|
}
|
||
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
||
|
return
|
||
|
ok:
|
||
|
handler(w, r)
|
||
|
if 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)
|
||
|
}
|
||
|
}
|