Search code examples
perlmojolicious

How can I omit the headers for a route when using Mojo?


Mojo seems to want add headers to the response. Is there any method to suppress headers given a context object?

$r->get('/')->to( cb => sub {
  my $c = shift;
  # No headers for this response
} );

Solution

  • In my case, I was using Mojo::Server::CGI. You can see the problems on line 29 and on line 35

    return undef if $self->nph && !_write($res, 'get_start_line_chunk');
    ...
    return undef unless _write($res, 'get_header_chunk');
    

    You can get around this by mucking with the internals,

    $c->res->content->_headers->{header_buffer} = '';                                                                          
    $c->res->{start_buffer} = '';
    

    But an even better way to is detect if anything has been written to STDOUT and to suppress the whole request if so,

    # We withhold headers if anything has written to
    # STDOUT. This is neccessary because some scripts, in-transition
    # to Mojo will still use `print`, and output headers
    if ( tell(*STDOUT) != 0 ) {
      return undef;
    }
    

    That what I did anyway when I published Mojo::Server::CGI::LegacyMigrate