Skip to content

Instantly share code, notes, and snippets.

View kraih's full-sized avatar

Sebastian Riedel kraih

View GitHub Profile
use 5.16.1;
use Mojo::UserAgent;
# Fetch web site
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get('mojolicio.us/perldoc');
# Extract title
say 'Title: ', $tx->res->dom->at('head > title')->text;
package Mojolicious::Plugin::Pipeline::CSSCompressor;
use Mojo::Base 'Mojolicious::Plugin';
use CSS::Compressor 'css_compress';
sub register {
my ($self, $app) = @_;
# Register "css_compressor" filter
$app->filter(css_compressor => sub { css_compress shift });
use warnings;
use strict;
use feature ':5.10';
use B;
# Type and flags for reference
my $obj = B::svref_2object(\(my $dummy = !!1));
my $TYPE = $obj->SvTYPE;
my $FLAGS = $obj->FLAGS;
package Mojolicious::Plugin::GZip;
use Mojo::Base 'Mojolicious::Plugin';
use IO::Compress::Gzip 'gzip';
# Just set "gzip => 1" in the stash and it will try to compress your content
sub register {
my ($self, $app) = @_;
$app->hook(
after_dispatch => sub {
package Mojolicious::Lite::GetPost;
use Mojo::Base -base;
use Mojo::Util 'monkey_patch';
sub import {
my $caller = caller;
monkey_patch $caller, 'get_post', sub {
return $caller->app->routes->any([qw(GET POST)] => @_);
};
package Mojolicious::Lite::MyKeywords;
use Mojo::Base -base;
use Mojo::Util 'monkey_patch';
sub import {
my $caller = caller;
# Export "get_post" keyword (reuse "any" keyword to make "under" work)
monkey_patch $caller, 'get_post', sub {
@kraih
kraih / mango_app.pl
Last active December 12, 2015 10:09
use Mojolicious::Lite;
use Mango;
use Mango::BSON ':bson';
my $uri = 'mongodb://<user>:<pass>@<server>/<database>';
helper mango => sub { state $mango = Mango->new($uri) };
# Store and retrieve information non-blocking
get '/' => sub {
my $self = shift;
@kraih
kraih / c10k.pl
Last active March 20, 2021 14:33
#
# Open 10k concurrent WebSocket connections with the client and server running
# in the same process and perform 10k WebSocket message roundtrips
#
# Tested on OS X 10.9.2 (MacBook Air) with Perl 5.18.2 and EV 4.17 (kqueue)
#
# 560.9MB memory usage, 0% CPU usage once roundtrips are finished after 36s
# (with all 20k sockets still open)
#
# Get the latest version of Mojolicious from http://github.com/kraih/mojo
#!/usr/bin/env perl
use Mojolicious::Lite;
use Coro;
use Mojo::IOLoop;
# Magical class for calling a method non-blocking (with a closure) and
# rescheduling the current coroutine until it is done
package with::coro {
use Coro;
@kraih
kraih / Coro.pm
Last active April 19, 2019 13:48
package Mojolicious::Plugin::Coro;
use Mojo::Base 'Mojolicious::Plugin';
use Coro;
use Mojo::IOLoop;
# Wrap application in coroutine and reschedule main coroutine in event loop
sub register {
my ($self, $app) = @_;
my $subscribers = $app->plugins->subscribers('around_dispatch');