CGI-Tiny

 view release on metacpan or  search on metacpan

README  view on Meta::CPAN

METHODS

    The following methods can be called on the CGI::Tiny object provided to
    the cgi block.

 Setup

  set_error_handler

      $cgi = $cgi->set_error_handler(sub {
        my ($cgi, $error, $rendered) = @_;
        ...
      });

    Sets an error handler to run in the event of an exception or if the
    script ends without rendering a response. The handler will be called
    with the CGI::Tiny object, the error value, and a boolean indicating
    whether response headers have been rendered yet.

    The error value can be any exception thrown by Perl or user code. It
    should generally not be included in any response rendered to the
    client, but instead warned or logged.

    Exceptions may occur before or after response headers have been
    rendered. If response headers have not been rendered, error handlers
    may inspect "response_status_code" and/or render some error response.
    The response status code will be set to 500 when this handler is called
    if it has not been set to a specific 400- or 500-level error status.

    If the error handler itself throws an exception, that error and the
    original error will be emitted as a warning. If no response has been
    rendered after the error handler completes or dies, a default error
    response will be rendered.

    NOTE: The error handler is only meant for logging and customization of
    the final error response in a failed request dispatch; to handle
    exceptions within standard application flow without causing an error
    response, use an exception handling mechanism such as
    Syntax::Keyword::Try or Feature::Compat::Try (which will use the new
    try feature if available).

  set_request_body_buffer

      $cgi = $cgi->set_request_body_buffer(256*1024);

    Sets the buffer size (number of bytes to read at once) for reading the
    request body. Defaults to the value of the CGI_TINY_REQUEST_BODY_BUFFER
    environment variable or 262144 (256 KiB). A value of 0 will use the
    default value.

  set_request_body_limit

      $cgi = $cgi->set_request_body_limit(16*1024*1024);

    Sets the limit in bytes for the request body. Defaults to the value of
    the CGI_TINY_REQUEST_BODY_LIMIT environment variable or 16777216 (16
    MiB). A value of 0 will remove the limit (not recommended unless you
    have other safeguards on memory usage).

    Since the request body is not parsed until needed, methods that parse
    the request body like "body" or "upload" will set the response status
    to 413 Payload Too Large and throw an exception if the content length
    is over the limit. Files uploaded through a multipart/form-data request
    body also count toward this limit, though they are streamed to
    temporary files when parsed.

  set_multipart_form_options

      $cgi = $cgi->set_multipart_form_options({discard_files => 1, tempfile_args => [SUFFIX => '.dat']});

    Set a hash reference of options to pass when parsing a
    multipart/form-data request body with "parse_multipart_form_data" in
    CGI::Tiny::Multipart. No effect after the form data has been parsed
    such as by calling "body_params" or "uploads" for the first time.

    NOTE: Options like parse_as_files and on_file_buffer can alter the
    content and file keys of the form field structure returned by
    "body_parts". Thus "uploads" may not contain file and may instead
    contain content, and "body_params" text field values may be read from
    file, which will be expected to be a seekable filehandle if present.

  set_multipart_form_charset

      $cgi = $cgi->set_multipart_form_charset('UTF-8');

    Sets the default charset for decoding multipart/form-data forms,
    defaults to UTF-8. Parameter and upload field names, upload filenames,
    and text parameter values that don't specify a charset will be decoded
    from this charset. Set to an empty string to disable this decoding,
    effectively interpreting such values in ISO-8859-1.

  set_input_handle

      $cgi = $cgi->set_input_handle($fh);

    Sets the input handle to read the request body from. If not set, reads
    from STDIN. The handle will have binmode applied before reading to
    remove any translation layers.

  set_output_handle

      $cgi = $cgi->set_output_handle($fh);

    Sets the output handle to print the response to. If not set, prints to
    STDOUT. The handle will have binmode applied before printing to remove
    any translation layers.

 Request Environment

    CGI::Tiny provides direct access to CGI request meta-variables
    <https://tools.ietf.org/html/rfc3875#section-4.1> via methods that map
    to the equivalent uppercase names (and a few short aliases). Since CGI
    does not distinguish between missing and empty values, missing values
    will be normalized to an empty string.

  auth_type

      # AUTH_TYPE="Basic"
      my $auth_type = $cgi->auth_type;

    The authentication scheme used in the Authorization HTTP request header
    if any.

  content_length

      # CONTENT_LENGTH="42"
      my $content_length = $cgi->content_length;

    The size in bytes of the request body content if any.

  content_type

      # CONTENT_TYPE="text/plain;charset=UTF-8"
      my $content_type = $cgi->content_type;

    The MIME type of the request body content if any.

  gateway_interface

      # GATEWAY_INTERFACE="CGI/1.1"
      my $gateway_inteface = $cgi->gateway_interface;

    The CGI version used for communication with the CGI server.

  path_info

  path

README  view on Meta::CPAN

    NOTE: This will read the text form fields into memory as in
    "body_params".

  param_array

      my $arrayref = $cgi->param_array('foo');

    Retrieve values of a named URL query string parameter or
    application/x-www-form-urlencoded or multipart/form-data body
    parameter, decoded to Unicode characters, as an ordered array
    reference.

    Query parameter values will be returned first, followed by body
    parameter values. Use "query_param_array" or "body_param_array" to
    retrieve query or body parameter values separately.

    NOTE: This will read the text form fields into memory as in
    "body_params".

  query_params

      my $pairs = $cgi->query_params;

    Retrieve URL query string parameters as an ordered array reference of
    name/value pairs, represented as two-element array references. Names
    and values are decoded to Unicode characters.

  query_param_names

      my $arrayref = $cgi->query_param_names;

    Retrieve URL query string parameter names, decoded to Unicode
    characters, as an ordered array reference, without duplication.

  query_param

      my $value = $cgi->query_param('foo');

    Retrieve value of a named URL query string parameter, decoded to
    Unicode characters.

    If the parameter name was passed multiple times, returns the last
    value. Use "query_param_array" to get multiple values of a parameter.

  query_param_array

      my $arrayref = $cgi->query_param_array('foo');

    Retrieve values of a named URL query string parameter, decoded to
    Unicode characters, as an ordered array reference.

  body

      my $bytes = $cgi->body;

    Retrieve the request body as bytes.

    NOTE: This will read the whole request body into memory, so make sure
    the "set_request_body_limit" can fit well within the available memory.

    Not available after calling "body_parts", "body_params", or "uploads"
    (or related accessors) on a multipart/form-data request, since this
    type of request body is not retained in memory after parsing.

  body_json

      my $data = $cgi->body_json;

    Decode an application/json request body from UTF-8-encoded JSON.

    NOTE: This will read the whole request body into memory, so make sure
    the "set_request_body_limit" can fit well within the available memory.

  body_params

      my $pairs = $cgi->body_params;

    Retrieve application/x-www-form-urlencoded or multipart/form-data body
    parameters as an ordered array reference of name/value pairs,
    represented as two-element array references. Names and values are
    decoded to Unicode characters.

    NOTE: This will read the text form fields into memory, so make sure the
    "set_request_body_limit" can fit well within the available memory.
    multipart/form-data file uploads will be streamed to temporary files
    accessible via "uploads" and related methods.

  body_param_names

      my $arrayref = $cgi->body_param_names;

    Retrieve application/x-www-form-urlencoded or multipart/form-data body
    parameter names, decoded to Unicode characters, as an ordered array
    reference, without duplication.

    NOTE: This will read the text form fields into memory as in
    "body_params".

  body_param

      my $value = $cgi->body_param('foo');

    Retrieve value of a named application/x-www-form-urlencoded or
    multipart/form-data body parameter, decoded to Unicode characters.

    If the parameter name was passed multiple times, returns the last
    value. Use "body_param_array" to get multiple values of a parameter.

    NOTE: This will read the text form fields into memory as in
    "body_params".

  body_param_array

      my $arrayref = $cgi->body_param_array('foo');

    Retrieve values of a named application/x-www-form-urlencoded or
    multipart/form-data body parameter, decoded to Unicode characters, as
    an ordered array reference.

    NOTE: This will read the text form fields into memory as in
    "body_params".

  body_parts

      my $parts = $cgi->body_parts;

    Retrieve multipart/form-data request body parts as an ordered array
    reference using "parse_multipart_form_data" in CGI::Tiny::Multipart.
    Most applications should retrieve multipart form data through
    "body_params" and "uploads" (or related accessors) instead.

    NOTE: This will read the text form fields into memory, so make sure the
    "set_request_body_limit" can fit well within the available memory. File
    uploads will be streamed to temporary files.

  uploads

      my $pairs = $cgi->uploads;

    Retrieve multipart/form-data file uploads as an ordered array reference
    of name/upload pairs, represented as two-element array references.
    Names are decoded to Unicode characters.

    NOTE: This will read the text form fields into memory, so make sure the
    "set_request_body_limit" can fit well within the available memory.

    File uploads are represented as a hash reference containing the
    following keys:

    filename

      Original filename supplied to file input. An empty filename may
      indicate that no file was submitted.

    content_type

      Content-Type of uploaded file, undef if unspecified.

    size

      File size in bytes.

    file

      File::Temp object storing the file contents in a temporary file,
      which will be cleaned up when the CGI script ends by default. The
      filehandle will be open with the seek pointer at the start of the
      file for reading.

  upload_names

      my $arrayref = $cgi->upload_names;

    Retrieve multipart/form-data file upload names, decoded to Unicode
    characters, as an ordered array reference, without duplication.

    NOTE: This will read the text form fields into memory as in "uploads".

  upload

      my $upload = $cgi->upload('foo');

    Retrieve a named multipart/form-data file upload. If the upload name
    was passed multiple times, returns the last value. Use "upload_array"
    to get multiple uploads with the same name.

    See "uploads" for details on the representation of the upload.

    NOTE: This will read the text form fields into memory as in "uploads".

  upload_array

      my $arrayref = $cgi->upload_array('foo');

    Retrieve all multipart/form-data file uploads of the specified name as
    an ordered array reference.

    See "uploads" for details on the representation of the uploads.

    NOTE: This will read the text form fields into memory as in "uploads".

 Response

  set_nph

      $cgi = $cgi->set_nph;
      $cgi = $cgi->set_nph(1);

    If set to a true value or called without a value before rendering
    response headers, CGI::Tiny will act as a NPH (Non-Parsed Header)
    <https://tools.ietf.org/html/rfc3875#section-5> script and render full
    HTTP response headers. This may be required for some CGI servers, or
    enable unbuffered responses or HTTP extensions not supported by the CGI
    server.

    No effect after response headers have been rendered.

  set_response_body_buffer

      $cgi = $cgi->set_response_body_buffer(128*1024);

    Sets the buffer size (number of bytes to read at once) for streaming a
    file or handle response body with "render" or "render_chunk". Defaults
    to the value of the CGI_TINY_RESPONSE_BODY_BUFFER environment variable
    or 131072 (128 KiB). A value of 0 will use the default value.

  set_response_status

      $cgi = $cgi->set_response_status(404);
      $cgi = $cgi->set_response_status('500 Internal Server Error');

    Sets the response HTTP status code. A full status string including a
    human-readable message will be used as-is. A bare status code must be a
    known HTTP status code
    <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml>
    and will have the standard human-readable message appended.

    No effect after response headers have been rendered.

    The CGI protocol assumes a status of 200 OK if no response status is
    set.

  set_response_disposition

      $cgi = $cgi->set_response_disposition('attachment');
      $cgi = $cgi->set_response_disposition(attachment => $filename);
      $cgi = $cgi->set_response_disposition('inline'); # default behavior
      $cgi = $cgi->set_response_disposition(inline => $filename);

    Sets the response Content-Disposition header to indicate how the client
    should present the response, with an optional filename specified in
    Unicode characters. attachment suggests to download the content as a
    file, and inline suggests to display the content inline (the default
    behavior). No effect after response headers have been rendered.

  set_response_type

      $cgi = $cgi->set_response_type('application/xml');

    Sets the response Content-Type header, to override autodetection in

README  view on Meta::CPAN

    the specified "request_method". A following URL parameter will be
    passed as the "path_info" and "query_string" if present.

    Request content may be provided through STDIN but the Content-Length
    request header must be set to the size of the input as required by the
    CGI spec.

    The response will be printed to STDOUT as normal. You may wish to
    redirect the output of the command to a file or hexdump program if the
    response is expected not to be printable text in the character encoding
    of your terminal.

    Options may follow the command:

    --content=<string>, -c <string>

      Passes the string value as request body content and sets the
      Content-Length request header to its size.

    --cookie=<string>, -C <string>

      String values of the form name=value will be passed as request
      cookies. Can appear multiple times.

    --header=<string>, -H <string>

      String values of the form Name: value will be passed as request
      headers. Can appear multiple times. If the same header name is
      provided multiple times, the values will be joined with commas, which
      is only valid for certain headers.

    --verbose, -v

      Includes response CGI headers (or HTTP headers in NPH mode) in the
      output before response content. Enabled automatically for head.

COMPARISON TO CGI.PM

    Traditionally, the CGI module (referred to as CGI.pm to differentiate
    it from the CGI protocol) has been used to write Perl CGI scripts. This
    module fills a similar need but has a number of interface differences
    to be aware of.

      * There is no CGI::Tiny object constructor; the object is accessible
      within the cgi block, only reads request data from the environment
      once it is accessed, and ensures that a valid response is rendered to
      avoid gateway errors even in the event of an exception or premature
      exit.

      * Instead of global variables like $CGI::POST_MAX, global behavior
      settings are applied to the CGI::Tiny object inside the cgi block.

      * Exceptions within the cgi block are handled by default by rendering
      a server error response and emitting the error as a warning. This can
      be customized with "set_error_handler".

      * Request parameter accessors in CGI::Tiny are not context sensitive,
      as context sensitivity can lead to surprising behavior and
      vulnerabilities
      <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-1572>.
      "param", "query_param", "body_param", and "upload" always return a
      single value; "param_array", "query_param_array", "body_param_array",
      and "upload_array" must be used to retrieve multi-value parameters.

      * CGI::Tiny's "param" accessor is also not method-sensitive; it
      accesses either query or body request parameters with the same
      behavior regardless of request method, and query and body request
      parameters can be accessed separately with "query_param" and
      "body_param" respectively.

      * CGI::Tiny's "param" accessor only retrieves text parameters;
      uploaded files and their metadata are accessed with "upload" and
      related methods.

      * CGI::Tiny decodes request parameters to Unicode characters
      automatically, and "render"/"render_chunk" provide methods to encode
      response content from Unicode characters to UTF-8 by default.

      * In CGI.pm, response headers must be printed manually before any
      response content is printed to avoid malformed responses. In
      CGI::Tiny, the "render" or "render_chunk" methods are used to print
      response content, and automatically print response headers when first
      called. redirect responses are also handled by "render".

      * In CGI::Tiny, a custom response status is set by calling
      "set_response_status" before the first "render" or "render_chunk",
      which only requires the status code and will add the appropriate
      human-readable status message itself.

      * Response setters are distinct methods from request accessors in
      CGI::Tiny. "content_type", "header", and "cookie" are used to access
      request data, and "set_response_type", "add_response_header", and
      "add_response_cookie" are used to set response headers for the
      pending response before the first call to "render" or "render_chunk".

      * CGI::Tiny does not provide any HTML generation helpers, as this
      functionality is much better implemented by other robust
      implementations on CPAN; see "Templating" in CGI::Tiny::Cookbook.

      * CGI::Tiny does not do any implicit encoding of cookie values or the
      Expires header or cookie attribute. See "Cookies" in
      CGI::Tiny::Cookbook for examples of encoding and decoding cookie
      values. The "epoch_to_date" convenience function is provided to
      render appropriate Expires date values.

    There are a number of alternatives to CGI.pm but they do not
    sufficiently address the design issues; primarily, none of them
    gracefully handle exceptions or failure to render a response, and
    several of them have no features for rendering responses.

      * CGI::Simple shares all of the interface design problems of CGI.pm,
      though it does not reimplement the HTML generation helpers.

      * CGI::Thin is ancient and only implements parsing of request query
      or body parameters, without decoding them to Unicode characters.

      * CGI::Minimal has context-sensitive parameter accessors, and only
      implements parsing of request query/body parameters (without decoding
      them to Unicode characters) and uploads.

      * CGI::Lite has context-sensitive parameter accessors, and only
      implements parsing of request query/body parameters (without decoding
      them to Unicode characters), uploads, and cookies.

      * CGI::Easy has a robust interface, but pre-parses all request
      information.

CAVEATS

    CGI is an extremely simplistic protocol and relies particularly on the
    global state of environment variables and the STDIN and STDOUT standard
    filehandles. CGI::Tiny does not prevent you from messing with these
    interfaces directly, but it may result in confusion.

    CGI::Tiny eschews certain sanity checking for performance reasons. For
    example, Content-Type and other header values set for the response
    should only contain ASCII text with no control characters, but
    CGI::Tiny does not verify this (though it does verify they do not
    contain newline characters to protect against HTTP response splitting).

    Field names and filenames in multipart/form-data requests do not have a
    well-defined escape mechanism for special characters, so CGI::Tiny will
    not attempt to decode these names from however the client passes them
    aside from "set_multipart_form_charset". For best compatibility, form
    field names should be ASCII without double quotes or semicolons.

BUGS

    Report any issues on the public bugtracker.

AUTHOR

    Dan Book <dbook@cpan.org>

COPYRIGHT AND LICENSE

    This software is Copyright (c) 2021 by Dan Book.

    This is free software, licensed under:

      The Artistic License 2.0 (GPL Compatible)

SEE ALSO

    CGI::Alternatives, Mojolicious, Dancer2



( run in 1.663 second using v1.01-cache-2.11-cpan-b16cb0d3907 )