This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/utils/http.go
Tim Wundenberg 521119fc02
All checks were successful
Build Docker Image / Build-Docker-Image (push) Successful in 44s
Build and Push Docker Image / Build-And-Push-Docker-Image (push) Successful in 48s
fix: refine logging
2024-12-04 22:04:32 +01:00

46 lines
954 B
Go

package utils
import (
"me-fit/log"
"fmt"
"net/http"
"time"
)
func TriggerToast(w http.ResponseWriter, r *http.Request, class string, message string) {
if isHtmx(r) {
w.Header().Set("HX-Trigger", fmt.Sprintf(`{"toast": "%v|%v"}`, class, message))
} else {
log.Error("Trying to trigger toast in non-HTMX request")
}
}
func DoRedirect(w http.ResponseWriter, r *http.Request, url string) {
if isHtmx(r) {
w.Header().Add("HX-Redirect", url)
} else {
http.Redirect(w, r, url, http.StatusSeeOther)
}
}
func WaitMinimumTime[T interface{}](waitTime time.Duration, function func() (T, error)) (T, error) {
start := time.Now()
result, err := function()
time.Sleep(waitTime - time.Since(start))
return result, err
}
func GetSessionID(r *http.Request) string {
for _, c := range r.Cookies() {
if c.Name == "id" {
return c.Value
}
}
return ""
}
func isHtmx(r *http.Request) bool {
return r.Header.Get("HX-Request") == "true"
}