generated from ElnuDev/go-project
Rearrange repo as monorepo
This commit is contained in:
parent
2a59a96493
commit
848175efde
11 changed files with 216 additions and 172 deletions
12
httputils/event.go
Normal file
12
httputils/event.go
Normal file
|
@ -0,0 +1,12 @@
|
|||
package httputils
|
||||
|
||||
import "fmt"
|
||||
|
||||
type SseEvent struct {
|
||||
EventName string
|
||||
Data string
|
||||
}
|
||||
|
||||
func (event SseEvent) Encode() string {
|
||||
return fmt.Sprintf("event: %s\ndata: %s\n\n", event.EventName, event.Data)
|
||||
}
|
50
httputils/handler.go
Normal file
50
httputils/handler.go
Normal file
|
@ -0,0 +1,50 @@
|
|||
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)
|
||||
}
|
||||
}
|
Reference in a new issue