caddy-keydb-codebreaker/errors.go

72 lines
1.9 KiB
Go
Raw Normal View History

2024-08-14 13:11:08 -07:00
package guardianextension
2024-08-13 16:28:06 -07:00
import (
"encoding/json"
"fmt"
"net/http"
"sync"
)
2024-08-14 13:11:08 -07:00
// GuardianError is a custom error type that includes an HTTP status code and a message.
type GuardianError struct {
Code int
Message string
}
func (e *GuardianError) Error() string {
return e.Message
}
var (
ErrNoAuthToken = &GuardianError{401, "No auth token provided"}
ErrUnauthorized = &GuardianError{403, "Unauthorized access"}
ErrIncompleteReq = &GuardianError{400, "Request was incomplete"}
ErrConnFailed = &GuardianError{523, "Connection to GuardianPT failed"}
ErrReqNotProcessed = &GuardianError{522, "Request could not be processed"}
ErrUnknown = &GuardianError{520, "An unknown error occurred"}
ErrAuthTokenTooLong = &GuardianError{494, "Invalid auth token length"}
2024-08-13 16:28:06 -07:00
)
var (
errorResponsesOnce sync.Once
)
2024-08-14 13:11:08 -07:00
// initErrorResponses initializes the error response and status code maps.
// It defines a set of standard error responses and their associated HTTP status codes.
2024-08-13 16:28:06 -07:00
func initErrorResponses() {
2024-08-14 13:11:08 -07:00
errors := []*GuardianError{
ErrNoAuthToken,
ErrUnauthorized,
ErrIncompleteReq,
ErrConnFailed,
ErrReqNotProcessed,
ErrUnknown,
ErrAuthTokenTooLong,
2024-08-13 16:28:06 -07:00
}
for _, err := range errors {
2024-08-14 13:11:08 -07:00
error_code := fmt.Sprintf("0x%08X", 0xC0043293+err.Code)
2024-08-13 16:28:06 -07:00
response, _ := json.Marshal(map[string]interface{}{
"error": true,
"code": error_code,
2024-08-14 13:11:08 -07:00
"message": err.Message,
2024-08-13 16:28:06 -07:00
})
2024-08-14 13:11:08 -07:00
// Overwrite error message as string for less space allocation
err.Message = string(response)
2024-08-13 16:28:06 -07:00
}
}
2024-08-14 13:11:08 -07:00
// sendJSONError writes a JSON-formatted error response to the provided http.ResponseWriter.
func sendJSONError(w http.ResponseWriter, err error) {
2024-08-13 16:28:06 -07:00
errorResponsesOnce.Do(initErrorResponses)
2024-08-14 13:11:08 -07:00
customErr, ok := err.(*GuardianError)
if !ok {
customErr = ErrUnknown
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(customErr.Code)
w.Write([]byte(customErr.Message))
2024-08-13 16:28:06 -07:00
}