package guardianextension import ( "encoding/json" "fmt" "net/http" "sync" ) // 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"} ) var ( errorResponsesOnce sync.Once ) // initErrorResponses initializes the error response and status code maps. // It defines a set of standard error responses and their associated HTTP status codes. func initErrorResponses() { errors := []*GuardianError{ ErrNoAuthToken, ErrUnauthorized, ErrIncompleteReq, ErrConnFailed, ErrReqNotProcessed, ErrUnknown, ErrAuthTokenTooLong, } for _, err := range errors { error_code := fmt.Sprintf("0x%08X", 0xC0043293+err.Code) response, _ := json.Marshal(map[string]interface{}{ "error": true, "code": error_code, "message": err.Message, }) // Overwrite error message as string for less space allocation err.Message = string(response) } } // sendJSONError writes a JSON-formatted error response to the provided http.ResponseWriter. func sendJSONError(w http.ResponseWriter, err error) { errorResponsesOnce.Do(initErrorResponses) customErr, ok := err.(*GuardianError) if !ok { customErr = ErrUnknown } w.Header().Set("Content-Type", "application/json") w.WriteHeader(customErr.Code) w.Write([]byte(customErr.Message)) }