Files
oslstats/internal/throw/throw.go

119 lines
2.6 KiB
Go

// Package throw provides utility functions for throwing HTTP errors that render an error page
package throw
import (
"fmt"
"net/http"
"git.haelnorr.com/h/golib/hws"
"github.com/pkg/errors"
)
// throwError is a generic helper that all throw* functions use internally
func throwError(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
statusCode int,
msg string,
err error,
level hws.ErrorLevel,
) {
s.ThrowError(w, r, hws.HWSError{
StatusCode: statusCode,
Message: msg,
Error: err,
Level: level,
RenderErrorPage: true, // throw* family always renders error pages
})
}
// InternalServiceError handles 500 errors (server failures)
func InternalServiceError(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusInternalServerError, msg, err, hws.ErrorERROR)
}
// ServiceUnavailable handles 503 errors
func ServiceUnavailable(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusServiceUnavailable, msg, err, hws.ErrorERROR)
}
// BadRequest handles 400 errors (malformed requests)
func BadRequest(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusBadRequest, msg, err, hws.ErrorDEBUG)
}
// Forbidden handles 403 errors (normal permission denials)
func Forbidden(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusForbidden, msg, err, hws.ErrorDEBUG)
}
// ForbiddenSecurity handles 403 errors for security events (uses WARN level)
func ForbiddenSecurity(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusForbidden, msg, err, hws.ErrorWARN)
}
// Unauthorized handles 401 errors (not authenticated)
func Unauthorized(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusUnauthorized, msg, err, hws.ErrorDEBUG)
}
// UnauthorizedSecurity handles 401 errors for security events (uses WARN level)
func UnauthorizedSecurity(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
msg string,
err error,
) {
throwError(s, w, r, http.StatusUnauthorized, msg, err, hws.ErrorWARN)
}
// NotFound handles 404 errors
func NotFound(
s *hws.Server,
w http.ResponseWriter,
r *http.Request,
path string,
) {
msg := fmt.Sprintf("The requested resource was not found: %s", path)
err := errors.New("Resource not found")
throwError(s, w, r, http.StatusNotFound, msg, err, hws.ErrorDEBUG)
}