Files
spend-sparrow/internal/core/http.go
Tim Wundenberg 1be46780bb
All checks were successful
Build and Push Docker Image / Build-And-Push-Docker-Image (push) Successful in 1m19s
feat: extract into remaining packages
There has been a cyclic dependency.
transaction
	-> treasure_chest
	-> transaction_recurring
	-> transaction

This has been temporarily solved by moving the GenerateTransactions
function into the transaction package. In the future, this function has
to be rewritten to use a proper Service insteas of direct DB access or
replaced with a different system entirely.
2025-12-31 22:26:59 +01:00

43 lines
1.1 KiB
Go

package core
import (
"context"
"fmt"
"log/slog"
"net/http"
"strings"
"time"
)
func TriggerToast(ctx context.Context, 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 {
slog.ErrorContext(ctx, "Trying to trigger toast in non-HTMX request")
}
}
func TriggerToastWithStatus(ctx context.Context, w http.ResponseWriter, r *http.Request, class string, message string, statusCode int) {
TriggerToast(ctx, 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 any](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"
}