72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
|
)
|
|
|
|
type ContextKey string
|
|
|
|
const (
|
|
ContextKeyUser ContextKey = "user_id"
|
|
)
|
|
|
|
var (
|
|
errorMetric = promauto.NewCounter(
|
|
prometheus.CounterOpts{
|
|
Name: "mefit_error_total",
|
|
Help: "The total number of errors during processing",
|
|
},
|
|
)
|
|
)
|
|
|
|
func LogError(message string, err error) {
|
|
slog.Error(message + ": " + err.Error())
|
|
errorMetric.Inc()
|
|
}
|
|
func LogErrorMsg(message string) {
|
|
slog.Error(message)
|
|
errorMetric.Inc()
|
|
}
|
|
|
|
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 {
|
|
LogErrorMsg("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"
|
|
}
|