43 lines
1.0 KiB
Go
43 lines
1.0 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"spend-sparrow/internal/log"
|
|
)
|
|
|
|
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, strings.ReplaceAll(message, `"`, `\"`)))
|
|
} else {
|
|
log.L.Error("Trying to trigger toast in non-HTMX request")
|
|
}
|
|
}
|
|
|
|
func TriggerToastWithStatus(w http.ResponseWriter, r *http.Request, class string, message string, statusCode int) {
|
|
TriggerToast(w, r, class, message)
|
|
w.WriteHeader(statusCode)
|
|
}
|
|
|
|
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, f func() (T, error)) (T, error) {
|
|
start := time.Now()
|
|
result, err := f()
|
|
time.Sleep(waitTime - time.Since(start))
|
|
return result, err
|
|
}
|
|
|
|
func IsHtmx(r *http.Request) bool {
|
|
return r.Header.Get("Hx-Request") == "true"
|
|
}
|