perlmason

Get full request URL in HTML::Mason


How do I get full request URI in a perl website using HTML::Mason? Or at least scheme used (http or https)?

Have tried $r->uri and $r->unparsed_uri but both return only path return the path component of the requested URL


Solution

  • Try accessing the environment variables HTTPS, SERVER_PORT, and REQUEST_URI. For example:

    mason_server.pl:

    use v5.38;
    use HTTP::Server::Simple::Mason;
    
    {
        package MyApp::Server;
        use base 'HTTP::Server::Simple::Mason';
    
        # Override 'mason_config' to provide the component root path
        sub mason_config {
            return ( comp_root => '/home/hakon/data/mason' );
        }
    }
    # Create and start the server listening on port 3000 using your subclass
    my $server = MyApp::Server->new(3000);
    $server->run();
    

    And in the comp_root folder I have this file:

    index.html:

    % my $scheme = $ENV{HTTPS} eq 'on' || $ENV{SERVER_PORT} == 443 ? 'https' : 'http';
    % my $request_uri = $ENV{REQUEST_URI};
    Scheme: <% $scheme %><br>
    Request URI: <% $request_uri %>
    

    After starting the server, you can visit http://localhost:3000/ to check the result..