• Stars
    star
    34
  • Rank 766,985 (Top 16 %)
  • Language
    Perl
  • License
    Other
  • Created about 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

sinatra-ish simple waf

NAME

Kossy - Sinatra-ish Simple and Clear web application framework

SYNOPSIS

% kossy-setup MyApp
% cd MyApp
% plackup app.psgi

## lib/MyApp/Web.pm

use Kossy;

get '/' => sub {
    my ( $self, $c )  = @_;
    $c->render('index.tx', { greeting => "Hello!" });
};

get '/json' => sub {
    my ( $self, $c )  = @_;
    my $result = $c->req->validator([
        'q' => {
            default => 'Hello',
            rule => [
                [['CHOICE',qw/Hello Bye/],'Hello or Bye']
            ],
        }
    ]);
    $c->render_json({ greeting => $result->valid->get('q') });
};

1;

## views/index.tx
: cascade base
: around content -> {
  <: $greeting :>
: }

DESCRIPTION

Kossy is Sinatra-ish Simple and Clear web application framework, which is based upon Plack, Router::Boom, Text::Xslate and build-in Form-Validator. That's suitable for small application and rapid development.

Kossy class

Kossy exports some methods to building application

CLASS METHODS for Kossy class

  • my $kossy = Kossy->new( root_dir => $root_dir );

    Create instance of the application object.

OBJECT METHODS for Kossy class

  • my $root_dir = $kossy->root_dir();

    accessor to root directory of the application

  • my $app = $kossy->psgi();

    return PSGI application

DISPATCHER METHODS for Kossy class

  • filter

    makes application wrapper like plack::middlewares.

      filter 'set_title' => sub {
          my $app:CODE = shift;
          sub {
              my ( $self:Kossy, $c:Kossy::Connection )  = @_;
              $c->stash->{site_name} = __PACKAGE__;
              $app->($self,$c);
          }
      };
    
  • get path:String => [[filters] =>] CODE

  • post path:String => [[filters] =>] CODE

    setup router and dispatch code

      get '/' => [qw/set_title/] => sub {
          my ( $self:Kossy, $c:Kossy::Connection )  = @_;
          $c->render('index.tx', { greeting => "Hello!" });
      };
    
      get '/json' => sub {
          my ( $self:Kossy, $c:Kossy::Connection )  = @_;
          $c->render_json({ greeting => "Hello!" });
      };
    

    dispatch code shall return Kossy::Response object or PSGI response ArrayRef or String.

  • router 'HTTP_METHOD'|['METHOD'[,'METHOD']] => path:String => [[filters] =>] CODE

    adds routing rule other than GET and POST

      router 'PUT' => '/put' => sub {
          my ( $self:Kossy, $c:Kossy::Connection )  = @_;
          $c->render_json({ greeting => "Hello!" });
      };
    

Kossy::Connection class

per-request object, herds request and response

OBJECT METHODS for Kossy::Connection class

  • req:Kossy::Request

  • res:Kossy::Response

  • stash:HashRef

  • args:HashRef

    path parameters captured by Router::Boom

      get '/user/:id' => sub {
          my ($self, $c) = @_;
          my $id = $c->args->{id};
          ...
      };
    
  • halt(status_code, message)

    die and response immediately

  • redirect($uri,status_code): Kossy::Response

  • render($file,$args): Kossy::Response

    calls Text::Xslate->render makes response. template files are searching in root_dir/views directory

    template syntax is Text::Xslate::Syntax::Kolon, can use Kossy::Connection object and fillinform block.

      ## template.tx
      : block form |  fillinform( $c.req ) -> {
      <head>
      <title><: $c.stash.title :></title>
      </head>
      <body>
      <form action="<: $c.req.uri_for('/post') :>">
      <input type="text" size="10" name="title" />
      <textarea name="body" rows="20" cols="90"></textarea>
      </form>
      </body>
      : }
    

    also can use Text::Xslate::Bridge::TT2Like and Number::Format methods in your template

  • render_json($args): Kossy::Response

    serializes arguments with JSON and makes response

    This method escapes '<', '>', and '+' characters by "\uXXXX" form. Browser don't detects the JSON as HTML. And also this module outputs "X-Content-Type-Options: nosniff" header for IEs.

    render_json have a JSON hijacking detection feature same as Amon2::Plugin::Web::JSON. This returns "403 Forbidden" response if following pattern request.

    • The request have 'Cookie' header.
    • The request doesn't have 'X-Requested-With' header.
    • The request contains /android/i string in 'User-Agent' header.
    • Request method is 'GET'

Kossy::Request

This class is child class of Plack::Request, decode query/body parameters automatically. Return value of $req->param(), $req->body_parameters, etc. is the decoded value.

OBJECT METHODS for Kossy::Request class

  • uri_for($path,$args):String

    build absolute URI with path and $args

      my $uri = $c->req->uri_for('/login',[ arg => 'Hello']);
    
  • validator($rule):Kossy::Validator::Result

    validate parameters using Kossy::Validator

      my $result = $c->req->validator([
        'q' => [['NOT_NULL','query must be defined']],
        'level' => {
            default => 'M',
            rule => [
                [['CHOICE',qw/L M Q H/],'invalid level char'],
            ],
        },
      ]);
    
      my $val = $result->valid('q');
      my $val = $result->valid('level');
    
  • body_parameters_raw

  • query_parameters_raw

  • parameters_raw

  • param_raw

    These methods are the accessor to raw values. 'raw' means the value is not decoded.

  • body_parameters

    Accessor to decoded body parameters. It's Hash::MultiValue object.

  • query_parameters

    Accessor to decoded query parameters. It's Hash::MultiValue object.

  • json_parameters

    Accessor to decoded JSON body parameters. It's NOT Hash::MultiValue object.

      post '/api' => sub {
          my ($self, $c) = @_;
          my $foo = $c->req->json_parameters->{foo}; # bar
      };
    
      # requrest
      # $ua->requrest(
      #     HTTP::Request->new(
      #         "POST",
      #         "http://example.com/api",
      #         [ "Content-Type" => 'application/json', "Content-Length" => 13 ],
      #         '{"foo":"bar"}'
      #     )
      # );
    

    NOTE: Not need to set kossy.request.parse_json_body to 1

Kossy::Response

This class is child class of Plack::Response

CUSTOMIZE

  • X-Frame-Options

    By default, Kossy outputs "X-Frame-Options: DENY". You can change this header

      get '/iframe' => sub {
          my ($self, $c) = @_;
          $c->res->header('X-Frame-Options','SAMEORIGIN');
          # or remove from response header
          # delete $c->res->headers->remove_header('X-Frame-Options');
          ..
      }
    

    (Default: DENY)

  • kossy.request.parse_json_body

    If enabled, Kossy will decode json in the request body that has "application/json" content header

      post '/api' => sub {
          my ($self, $c) = @_;
          $c->env->{'kossy.request.parse_json_body'} = 1;
          my val = $c->req->param('foo'); # bar
      }
    
      # requrest
      # $ua->requrest(
      #     HTTP::Request->new(
      #         "POST",
      #         "http://example.com/api",
      #         [ "Content-Type" => 'application/json', "Content-Length" => 13 ],
      #         '{"foo":"bar"}'
      #     )
      # );
    
  • $XSLATE_CACHE, $XSLATE_CACHE_DIR

    Change xslate's cache level and cache directory.

      local $Kossy::XSLATE_CACHE = 2;
      local $Kossy::XSLATE_CACHE_DIR = $dir;
      my $app = MyApp::Web->psgi;
    

    By default, $XSLATE_CACHE is 1, $XSLATE_CACHE_DIR is undef. use Xslate's default.

  • $SECURITY_HEADER

    If disabled, Kossy does not set X-Frame-Options and X-XSS-Protection. enabled by default.

      local $Kossy::SECURITY_HEADER = 0;
      my $app = MyApp::Web->psgi;
    

    Can not change $Kossy::SECURITY_HEADER in your WebApp. It's need to set at build time.

    This is useful for the benchmark :-)

  • $JSON_SERIALIZER

    changes the JSON serializer:

      use Cpanel::JSON::XS;
      use Cpanel::JSON::XS::Type;
    
      local $Kossy::JSON_SERIALIZER = Cpanel::JSON::XS->new()->allow_blessed(1)->convert_blessed(1)->ascii(0);
    
      get '/' => sub {
          my ($self, $c) = @_;
          return $c->render_json({ a => '234' }, { a => JSON_TYPE_INT });
      };
    
      my $app = __PACKAGE__->psgi;
    

AUTHOR

Masahiro Nagano <kazeburo {at} gmail.com>

SEE ALSO

Kossy is small waf, that has only 400 lines code. so easy to reading framework code and customize it. Sinatra-ish router, build-in templating, validators and zero-configuration features are suitable for small application and rapid development.

Amon2::Lite

Mojolicious::Lite

Dancer

Kossy::Validator

LICENSE of HTTP::Headers::Fast

Kossy::Headers uses HTTP::Headers::Fast code. Here is LICENSE of HTTP::Headers::Fast

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

LICENSE

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

More Repositories

1

rhebok

High Performance Preforked Rack Handler
C
240
star
2

GrowthForecast

Lightning Fast Graphing/Visualization
Perl
233
star
3

cloudforecast

the server metrics gathering
Perl
149
star
4

chocon

chocon is a simple proxy server for persisting connections between upstream servers.
Go
142
star
5

mysetup

my setup scripts repository
Shell
134
star
6

Gazelle

Preforked Plack Handler for performance freaks
Perl
73
star
7

Kurado

monitor metrics
Perl
71
star
8

Monoceros

PSGI/Plack server with event driven connection manager, preforking workers
Perl
55
star
9

HRForecast

Perl
49
star
10

Proclet

minimalistic Supervisor
Perl
37
star
11

wsgate-server

a websocket to tcp proxy/bridge server
Go
36
star
12

Plack-Middleware-ServerStatus-Lite

Plack-Middleware-ServerStatus-Lite
Perl
25
star
13

prefork_engine

a simple prefork server framework / ruby port of perl's Parallel::Prefork
Ruby
24
star
14

GreenBuckets

Perl
23
star
15

query-digester

pt-query-digest wrapper to make ops simple
Perl
23
star
16

Log-Minimal

Minimal Logger
Perl
23
star
17

pico_http_parser

Fast HTTP Parser using picohttpparser
Ruby
19
star
18

isucon2_hack

isucon2 hack
Perl
19
star
19

Redis-Jet

Yet another XS implemented Redis client
XS
18
star
20

custom-mackerel-plugins

my custom mackerel plugins
Perl
17
star
21

motarei

Simple tcp proxy for Docker Hot deploy
Go
17
star
22

go-jmx-get

tiny jmx client
Go
16
star
23

DBIx-Sunny

Perl
16
star
24

docker-h2o

Dockerfile for h2o HTTP Server with graceful restart support
Shell
12
star
25

Plack-Builder-Conditionals

Plack::Builder extension
Perl
11
star
26

Plack-Middleware-Expires

mod_expires for plack
Perl
11
star
27

wsgate-client

a websocket to tcp proxy/bridge client server
Go
10
star
28

Plack-Server-AnyEvent-Prefork

Prefork AnyEvent based HTTP Server
Perl
10
star
29

mackerel-plugin-axslog

Yet Another mackerel-plugin for analyzing and visualizing Acesslog
Go
10
star
30

mackerel-plugin-pinging

ICMP Ping RTT custom mackerel plugin
Go
9
star
31

Apache-LogFormat-Compiler

Compile LogFormat to perl-code
Perl
9
star
32

Cache-Memcached-IronPlate

Best practices for Cache::Memcached
Perl
9
star
33

Twiggy-Prefork

Preforking AnyEvent HTTP server for PSGI
Perl
9
star
34

myps

Like pgrep and pkill, grep MySQL processlist and kill threads.
Go
8
star
35

percentile

Go
8
star
36

sabo

bandwidth limiting pipe with collaborative capability
Go
8
star
37

Scope-Container

Perl
8
star
38

build_mysql_mroonga_rpm

build mysql_mroonga.rpm by Vagrant provisioners
Shell
8
star
39

JavaScript-Value-Escape

Perl
7
star
40

isucon3qualifier-myhack

Perl
7
star
41

ppdp

Proxy Protocol Dump Proxy
Go
7
star
42

Scope-Container-DBI

DB connection manager with Scope::Container
Perl
6
star
43

heroku-buildpack-perl-procfile

a Heroku buildpack that runs any perl applications from Procfile
6
star
44

Cookie-Baker

Cookie string generator
Perl
6
star
45

p5-Alien-RRDtool

Installation of RRDs.pm (Perl binding for RRDtool)
Perl
6
star
46

rpm

my rpm repository
6
star
47

NoNoPaste

yet another nopaste
Perl
6
star
48

mackerel-plugin-maxcpu

Go
6
star
49

jstat2gf

Perl
5
star
50

chunkview

chuncked trasnfer visualizer
Perl
5
star
51

Time-TZOffset

Show timezone offset strings like +0900
C
5
star
52

NoNoPaste-Cloud

dotcloud nonopaste
Perl
5
star
53

mysql40dump

mysqldump wrapper for MySQL 4.0
Perl
5
star
54

Plack-Middleware-DBIx-DisconnectAll

Disconnect all database connection at end of request
Perl
5
star
55

isucon5-elimination-public

Perl
5
star
56

POSIX-strftime-Compiler

Perl
5
star
57

HTTP-Entity-Parser

PSGI compliant HTTP Entity Parser
Perl
5
star
58

Plack-Middleware-Scope-Container

Perl
5
star
59

Data-Page-Navigation

adds methods for page navigation link to Data::Page
Perl
4
star
60

docker-perl-build

docker image of perl-build
Shell
4
star
61

Plack-App-PHPCGI

execute PHP script as CGI
Perl
4
star
62

http-dump-request

http-dump-request server and docker container for monitoring and tests
Go
4
star
63

mackerel-plugin-postfix-log

Read and analyze postfix logs
Go
4
star
64

vagrant-destroy-provisioner

vagrant-destroy-provisioner plugin allows a VM to be destroyed as a provisioning step.
Ruby
4
star
65

check_http2

Nagios check_http plugin alternative powered by Go
Go
3
star
66

isucon11-final

final isucasy XI
Vue
3
star
67

diff-detector

a tiny tool
Go
3
star
68

isucon_summer_class_2014

ISUCON ε€ζœŸθ¬›ηΏ’ 2014
Go
3
star
69

CoreListWeb

Module::CoreList Web
Perl
3
star
70

mssh

ssh tool
3
star
71

check-cert-net

Check a remote certification expiry using openssl s_client
Go
3
star
72

mackerel-plugin-log-counter

mackerel metric plugin for count lines in log
Go
3
star
73

Plack-Middleware-Log-Minimal

Perl
3
star
74

mod_copy_header

copy a response header to notes
C
3
star
75

wg-keygen-rep

wireguard keypair generator with salt string
Go
3
star
76

Module-Build-Pluggable-CPANfile

Include cpanfile
Perl
3
star
77

WWW-GoogleAnalytics-Mobile

PSGI Application of Google Analytics for Mobile and client
Perl
3
star
78

Cache-Isolator

Perl
3
star
79

check_memcached_val

nagios plugin for checking value in a memcached server
Perl
3
star
80

check-lastlog

Check users who have not logged in recently
Go
2
star
81

Redis-Tiny

deprecated
Perl
2
star
82

deteco

Simple auth server used JWT & public-key cryptography
Go
2
star
83

isucon5-final-public

Perl
2
star
84

isius

Ping/TCP/HTTP/HTTPS monitoring agent server
Go
2
star
85

mackerel-plugin-resolver-synthetic

mackerel plugin for monitoring dns server as linux resolver
Go
2
star
86

tanzak

γŸγ‚“γ–γ
Perl
2
star
87

go-check-mysql-msr

check multi source replication
Go
2
star
88

connstorm

Go
2
star
89

App-derived

run command periodically and calculate rate and check from network
Perl
2
star
90

Cache-Memcached-Fast-Safe

Cache::Memcached::Fast with sanitizing keys and fork-safe
Perl
2
star
91

DBIx-DSN-Resolver

Resolv hostname within dsn string
Perl
2
star
92

limilic2

Perl
2
star
93

ltsvparser

LTSV (Labeled Tab-separated Values) parser for Go language
Go
2
star
94

private-isu-challenge

Go
2
star
95

Plack-Middleware-AxsLog

Alternative AccessLog Middleware
Perl
2
star
96

the-rp

the reverse HTTP an TCP Reverse proxy supports asynchronous upstream resolution and some balancing strategy
Go
2
star
97

File-RotateLogs

Rotate log file
Perl
2
star
98

relaxlogs

CLI for lestrrat-go/file-rotatelogs
Go
2
star
99

AnyEvent-DNS-Cache-Simple

provides simple cache for AnyEvent::DNS
Perl
2
star
100

Time-Crontab

Parser for crontab date and time field
Perl
2
star