File: HelloWorld.pm

package info (click to toggle)
libmojolicious-perl 0.999926-1%2Bsqueeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,672 kB
  • ctags: 949
  • sloc: perl: 17,391; makefile: 4
file content (289 lines) | stat: -rw-r--r-- 7,024 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# Copyright (C) 2008-2010, Sebastian Riedel.

package Mojo::HelloWorld;

use strict;
use warnings;

use base 'Mojo';

use Data::Dumper;
use Mojo::Filter::Chunked;

# How is education supposed to make me feel smarter? Besides,
# every time I learn something new, it pushes some old stuff out of my brain.
# Remember when I took that home winemaking course,
# and I forgot how to drive?
sub new {
    my $self = shift->SUPER::new(@_);

    # This app should log only errors to STDERR
    $self->log->level('error');
    $self->log->path(undef);

    return $self;
}

sub handler {
    my ($self, $tx) = @_;

    # Default to 200
    $tx->res->code(200) unless $tx->is_websocket;

    # Dispatch to diagnostics functions
    return $self->_diag($tx) if index($tx->req->url->path, '/diag') == 0;

    # WebSocket
    return if $tx->is_websocket;

    # Hello world!
    $tx->res->headers->content_type('text/plain');
    $tx->res->body('Congratulations, your Mojo is working!');
}

sub _diag {
    my ($self, $tx) = @_;

    # Path
    my $path = $tx->req->url->path;
    $path =~ s/^\/diag//;

    # WebSocket
    return $self->_websocket($tx) if $path =~ /^\/websocket/;

    # Defaults
    $tx->res->headers->content_type('text/plain')
      unless $tx->res->headers->content_type;

    # Dispatch
    return $self->_chunked_params($tx) if $path =~ /^\/chunked_params/;
    return $self->_dump_env($tx)       if $path =~ /^\/dump_env/;
    return $self->_dump_params($tx)    if $path =~ /^\/dump_params/;
    return $self->_dump_tx($tx)        if $path =~ /^\/dump_tx/;
    return $self->_dump_url($tx)       if $path =~ /^\/dump_url/;
    return $self->_proxy($tx)          if $path =~ /^\/proxy/;

    # List
    $tx->res->headers->content_type('text/html');
    $tx->res->body(<<'EOF');
<!doctype html><html>
    <head><title>Mojo Diagnostics</title></head>
    <body>
        <a href="/diag/chunked_params">Chunked Request Parameters</a><br />
        <a href="/diag/dump_env">Dump Environment Variables</a><br />
        <a href="/diag/dump_params">Dump Request Parameters</a><br />
        <a href="/diag/dump_tx">Dump Transaction</a><br />
        <a href="/diag/dump_url">Dump Request URL</a><br />
        <a href="/diag/proxy">Proxy</a><br />
        <a href="/diag/websocket">WebSocket</a>
    </body>
</html>
EOF
}

sub _chunked_params {
    my ($self, $tx) = @_;

    # Chunked
    $tx->res->headers->transfer_encoding('chunked');

    # Chunks
    my $params = $tx->req->params->to_hash;
    my $chunks = [];
    for my $key (sort keys %$params) {
        push @$chunks, $params->{$key};
    }

    # Callback
    my $counter = 0;
    my $chunked = Mojo::Filter::Chunked->new;
    $tx->res->body(
        sub {
            my $self = shift;
            my $chunk = $chunks->[$counter] || '';
            $counter++;
            return $chunked->build($chunk);
        }
    );
}

sub _dump_env {
    my ($self, $tx) = @_;
    $tx->res->body(Dumper \%ENV);
}

sub _dump_params {
    my ($self, $tx) = @_;
    $tx->res->body(Dumper $tx->req->params->to_hash);
}

sub _dump_tx {
    my ($self, $tx) = @_;
    $tx->res->body(Dumper $tx);
}

sub _dump_url {
    my ($self, $tx) = @_;
    $tx->res->body(Dumper $tx->req->url);
}

sub _proxy {
    my ($self, $tx) = @_;

    # Proxy
    if (my $url = $tx->req->param('url')) {

        # Fetch
        $self->client->get(
            $url => sub {
                my ($self, $tx2) = @_;

                # Pass through content
                $tx->res->headers->content_type(
                    $tx2->res->headers->content_type);
                $tx->res->body($tx2->res->content->asset->slurp);
            }
        )->process;

        return;
    }

    # Async proxy
    if (my $url = $tx->req->param('async_url')) {

        # Pause transaction
        $tx->pause;

        # Fetch
        $self->client->async->get(
            $url => sub {
                my ($self, $tx2) = @_;

                # Resume transaction
                $tx->resume;

                # Pass through content
                $tx->res->headers->content_type(
                    $tx2->res->headers->content_type);
                $tx->res->body($tx2->res->content->asset->slurp);
            }
        )->process;

        return;
    }

    # Form
    my $url = $tx->req->url->to_abs;
    $url->path('/diag/proxy');
    $tx->res->headers->content_type('text/html');
    $tx->res->body(<<"EOF");
<!doctype html><html>
    <head><title>Mojo Diagnostics</title></head>
    <body>
        Sync:
        <form action="$url" method="GET">
            <input type="text" name="url" value="http://"/>
            <input type="submit" value="Fetch" />
        </form>
        <br />
        Async:
        <form action="$url" method="GET">
            <input type="text" name="async_url" value="http://"/>
            <input type="submit" value="Fetch" />
        </form>
    </body>
</html>
EOF
}

sub _websocket {
    my ($self, $tx) = @_;

    # WebSocket request
    if ($tx->is_websocket) {
        $tx->send_message('Congratulations, your Mojo is working!');
        return $tx->receive_message(
            sub {
                my ($tx, $message) = @_;
                return unless $message eq 'test 123';
                $tx->send_message('With WebSocket support!');
            }
        );
    }

    # WebSocket example
    my $url = $tx->req->url->to_abs;
    $url->scheme('ws');
    $url->path('/diag/websocket');
    $tx->res->headers->content_type('text/html');
    $tx->res->body(<<"EOF");
<!doctype html><html>
    <head>
        <title>Mojo Diagnostics</title>
        <script language="javascript">
            if ("WebSocket" in window) {
                ws = new WebSocket("$url");
                function wsmessage(event) {
                    data = event.data;
                    alert(data);
                }
                function wsopen(event) {
                    ws.send("test 123");
                }
                ws.onmessage = wsmessage;
                ws.onopen = wsopen;
            }
            else {
                alert("Sorry, your browser does not support WebSocket.");
            }
        </script>
    </head>
    <body>
        Testing WebSocket, please make sure you have JavaScript enabled.
    </body>
</html>
EOF
}

1;
__END__

=head1 NAME

Mojo::HelloWorld - Hello World!

=head1 SYNOPSIS

    use Mojo::Transaction::HTTP;
    use Mojo::HelloWorld;

    my $hello = Mojo::HelloWorld->new;
    my $tx = $hello->handler(Mojo::Transaction::HTTP->new);

=head1 DESCRIPTION

L<Mojo::HelloWorld> is the default L<Mojo> application, used mostly for
testing.

=head1 METHODS

L<Mojo::HelloWorld> inherits all methods from L<Mojo> and implements the
following new ones.

=head2 C<new>

    my $hello = Mojo::HelloWorld->new;

Construct a new L<Mojo::HelloWorld> application.

=head2 C<handler>

    $tx = $hello->handler($tx);

Handle request.

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.

=cut