fix: move implementation to "internal" package
This commit was merged in pull request #138.
This commit is contained in:
42
internal/utils/http.go
Normal file
42
internal/utils/http.go
Normal file
@@ -0,0 +1,42 @@
|
||||
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.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"
|
||||
}
|
||||
Reference in New Issue
Block a user