diff --git a/Changes b/Changes index 4c6b2412..9f615986 100644 --- a/Changes +++ b/Changes @@ -2,6 +2,7 @@ Revision history for HTTP-Message {{$NEXT}} - Add support for RFC 8187 encoded filenames (GH#115) (Zaki Mughal) + - Add status_message_with_fallback function that returns default status messages for unknown status codes. (GH#105,#114) (Robert Rothenberg) 6.18 2018-06-05 16:29:15Z - Revert status_message to original code (GH#111) (Theo van Hoesel) diff --git a/lib/HTTP/Status.pm b/lib/HTTP/Status.pm index 44aa5cd1..29cb8626 100644 --- a/lib/HTTP/Status.pm +++ b/lib/HTTP/Status.pm @@ -9,7 +9,7 @@ require 5.002; # because we use prototypes use base 'Exporter'; our @EXPORT = qw(is_info is_success is_redirect is_error status_message); -our @EXPORT_OK = qw(is_client_error is_server_error is_cacheable_by_default); +our @EXPORT_OK = qw(is_client_error is_server_error is_cacheable_by_default status_message_with_fallback); # Note also addition of mnemonics to @EXPORT below @@ -129,6 +129,18 @@ our %EXPORT_TAGS = ( sub status_message ($) { $StatusCode{$_[0]}; } +sub status_message_with_fallback ($) { + status_message( $_[0] ) + || ( + is_info( $_[0] ) ? 'OK' + : is_success( $_[0] ) ? 'OK' + : is_redirect( $_[0] ) ? 'Redirect' + : is_client_error( $_[0] ) ? 'Client Error' + : is_server_error( $_[0] ) ? 'Server Error' + : undef + ); +} + sub is_info ($) { $_[0] && $_[0] >= 100 && $_[0] < 200; } sub is_success ($) { $_[0] && $_[0] >= 200 && $_[0] < 300; } sub is_redirect ($) { $_[0] && $_[0] >= 300 && $_[0] < 400; } @@ -262,7 +274,18 @@ The status_message() function will translate status codes to human readable strings. The string is the same as found in the constant names above. If the $code is not registered in the L -then C is returned. +then C is returned. + +=item status_message_with_fallback( $code ) + +This function will return corresponding status message, if the code is +defined. Otherwise it will return a default message based on the +code range. + +Use this function instead of C if your code always +assumes that there is a defined status message. + +This function is not exported by default. =item is_info( $code ) diff --git a/t/status-message-with-fallback.t b/t/status-message-with-fallback.t new file mode 100644 index 00000000..d4043b03 --- /dev/null +++ b/t/status-message-with-fallback.t @@ -0,0 +1,19 @@ +use strict; +use warnings; + +use Test::More; +plan tests => 12; + +use HTTP::Status qw(status_message status_message_with_fallback); + +foreach my $code (100, 200, 300, 400, 500) { + is(status_message_with_fallback($code), status_message($code)); +} + +is(status_message_with_fallback(0), undef); +is(status_message_with_fallback(199), "OK"); +is(status_message_with_fallback(299), "OK"); +is(status_message_with_fallback(399), "Redirect"); +is(status_message_with_fallback(499), "Client Error"); +is(status_message_with_fallback(599), "Server Error"); +is(status_message_with_fallback(600), undef);