Files
oslstats/internal/notify/notify.go

64 lines
2.0 KiB
Go

// Package notify provides utility functions for sending notifications to clients
package notify
import (
"net/http"
"git.haelnorr.com/h/golib/hws"
"git.haelnorr.com/h/golib/notify"
"git.haelnorr.com/h/oslstats/internal/throw"
"github.com/pkg/errors"
)
func notifyClient(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
level notify.Level,
title, message, details string,
action any,
) {
subCookie, err := r.Cookie("ws_sub_id")
if err != nil {
throw.InternalServiceError(s, w, r, "Notification failed. Do you have cookies enabled?", errors.Wrap(err, "r.Cookie"))
return
}
subID := notify.Target(subCookie.Value)
nt := notify.Notification{
Target: subID,
Title: title,
Message: message,
Details: details,
Action: action,
Level: level,
}
s.NotifySub(nt)
}
// InternalServiceError notifies with error level
func InternalServiceError(s *hws.Server, w http.ResponseWriter, r *http.Request, msg string, err error) {
notifyClient(s, w, r, notify.LevelError, "Internal Service Error", msg,
SerializeErrorDetails(http.StatusInternalServerError, err), nil)
}
// ServiceUnavailable notifies with error level
func ServiceUnavailable(s *hws.Server, w http.ResponseWriter, r *http.Request, msg string, err error) {
notifyClient(s, w, r, notify.LevelError, "Service Unavailable", msg,
SerializeErrorDetails(http.StatusServiceUnavailable, err), nil)
}
// Warn notifies with warn level
func Warn(s *hws.Server, w http.ResponseWriter, r *http.Request, title, msg string, action any) {
notifyClient(s, w, r, notify.LevelWarn, title, msg, "", action)
}
// Info notifies with info level
func Info(s *hws.Server, w http.ResponseWriter, r *http.Request, title, msg string, action any) {
notifyClient(s, w, r, notify.LevelInfo, title, msg, "", action)
}
// Success notifies with success level
func Success(s *hws.Server, w http.ResponseWriter, r *http.Request, title, msg string, action any) {
notifyClient(s, w, r, notify.LevelSuccess, title, msg, "", action)
}