All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 46s
74 lines
1.4 KiB
Go
74 lines
1.4 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"me-fit/types"
|
|
"net/http"
|
|
|
|
"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 GetUser(r *http.Request) *types.User {
|
|
user := r.Context().Value(ContextKeyUser)
|
|
if user != nil {
|
|
return user.(*types.User)
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func GetSessionID(r *http.Request) types.SessionId {
|
|
for _, c := range r.Cookies() {
|
|
if c.Name == "id" {
|
|
return types.SessionId(c.Value)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func isHtmx(r *http.Request) bool {
|
|
return r.Header.Get("HX-Request") == "true"
|
|
}
|