Saturday, 4 February 2012

G-WAN World's fastest web server for C scripts

After my previous post on CGI, I continued to search for a FastCGI example written in C, for the mac and nginx. There is a post about it, but it was not working. However I found an awesome project, G-WAN, as web server build in ANSI C, super fast, at least from the charts reported on the web site. Another fantastic feature that G-WAN has, is the possibility to write C scripts, yes script! You put your scripts in a directory and when the script is called fro the browser it is compiled and served. G-WAN can serve hundreds of thousands of connections per second but the response time is much better than any other language and application server.

This is a Hello World! example, the code does not has to be compiled:

// ============================================================================
// C servlet sample for the G-WAN Web Application Server (http://trustleap.ch/)
// ----------------------------------------------------------------------------
// hello.c: just used with Lighty's Weighttp to benchmark a minimalist servlet
// ============================================================================
// imported functions:
// get_reply(): get a pointer on the
'reply' dynamic buffer from the server
// xbuf_cat(): like strcat(), but it works in the specified dynamic buffer
// ----------------------------------------------------------------------------
#include "gwan.h" // G-WAN exported functions

int main(int argc, char *argv[])
{
xbuf_cat(get_reply(argv), "Hello World!");

return 200; // return an HTTP code (200:
'OK')
}
// ============================================================================
// End of Source Code
// ============================================================================


Now start the server:

sudo ./gwan

and enjoy: http://localhost:8080/csp?hello1.c

I wonder if, in a near future, we will have a super fast REST backend with a thick Javascript interface made with Backbone.js and JQuery.

Friday, 3 February 2012

CGI script with Apache and C programming language

Dynamic web pages where born in 1993 when CGI was introduced. The most common language used was Perl, but C was used too. Today I just tried to write a CGI script for the first time in my life and I did it with C, like a real man. Find your CGI path, mine is:

$ sudo cat /etc/apache2/httpd.conf | grep ScriptAlias
ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1"

So in my Mac I can put my CGI scripts here: /Library/WebServer/CGI-Executables/.

I created a file, test.c with this content:

#include 
#include

int main(void) {
printf("Content-Type: text/plain;charset=us-ascii\n\n");
printf("Hello world\n\n");
printf("The C programming language\n\n");

time_t now;
struct tm *d;
char li[13];
time(&now);
d = localtime(&now);
strftime(li, 15, "%d/%m/%Y", d);
printf("Today is %s\n", li);

return 0;
}


I compiled the file and made it executable:

cc testc.c -o testc && chmod +x testc

And is saw the outcome here http://localhost/cgi-bin/testc.

This is the output:

Hello world

The C programming language

Today is 03/02/2012

CGI is very simple, you just need to print the content type with newline and carriage return, then you can output your dynamic HTML content.

Today FastCGI has replaced CGI and it is very popular and probably it is the best way to create dynamic web pages with the most performance possible: C + FastCGI. Another option, more sophisticated and with different way of use it is uWSGI, created by the Italian hosting company Unbit.it. Yesterday I an article about the usage of C++ as programming language for Facebook, in 2009 they could shutdown 22500 servers if they where using C++ instead of PHP. We all know that Facebook and up in creating a PHP compiler, to compile PHP in C++: HipHop

P.S.: charset shout be UTF-8 :-)

Thursday, 29 December 2011

PHP hosting on EC2

EC2 (Amazon Virtual servers) can be used as any other VPS, if you use EBS for storing your data and the cost is really low. But where EC2 really exceed is on building automatically scaling web hosting solutions. Web servers can be load balanced with Elastic Load Balancers, servers can be added on demand. Best tools to create and manage an infrastructure on EC2 are Chef and Puppet.

Create a basic Ruby app with Rack middleware - part 1

This post - or may be a series of posts - on Rack is intended to understand how modern Ruby frameworks work. Frameworks such as Sinatra or Ruby on Rails use Rack middleware to exchange requests and responses to application servers. Old time of CGI or FCGI are gone. The code below shows how simple is to start a ruby server to serve a 404 error page:

app = lambda do |env|
body = File.open(File.dirname(__FILE__)+'/404.html', 'r').read
[404, {'Content-Type' => 'text/html'}, [body]]
end

run app


Save the previous script in a file named config.ru. If you have a page 404.html in the same directory of config.ru and you run:

> rackup -p 3000

You will get the 404.html page by connecting to http://localhost:3000. Please notice the curly braces between body: it is needed by Ruby 1.9. The run app statement run the lambda we just created.

Convert ruby code to HTML to paste into your blog

I use the following script to read ruby code and output the HTML to the stdin of the shell:

require 'syntax/convertors/html'

code = File.read('code.rb')

convertor = Syntax::Convertors::HTML.for_syntax "ruby"
code_html = convertor.convert( code )

puts code_html


Put you ruby code in 'code.rb' and run

> ruby script_name.rb

Then cut and paste the content. You have to add the following CSS if you want to see your code properly formatted:

pre {
background-color: #f1f1f3;
color: #112;
padding: 10px;
font-size: 1.1em;
overflow: auto;
margin: 4px 0px;
width: 95%;
}



/* Syntax highlighting */
pre .normal {}
pre .comment { color: #005; font-style: italic; }
pre .keyword { color: #A00; font-weight: bold; }
pre .method { color: #077; }
pre .class { color: #074; }
pre .module { color: #050; }
pre .punct { color: #447; font-weight: bold; }
pre .symbol { color: #099; }
pre .string { color: #944; background: #FFE; }
pre .char { color: #F07; }
pre .ident { color: #004; }
pre .constant { color: #07F; }
pre .regex { color: #B66; background: #FEF; }
pre .number { color: #F99; }
pre .attribute { color: #5bb; }
pre .global { color: #7FB; }
pre .expr { color: #227; }
pre .escape { color: #277; }


The style of the CSS code above has been created by changing the type of highlighter:


convertor = Syntax::Convertors::HTML.for_syntax "css"

How to call a private method in Ruby

If you want to call a private method in Ruby - for any reason - you can use send, method and instance_eval:



class Foo

private
def bar
puts 'You called bar'
end
end

> foo = Foo.new
foo.bar # this, of course, throws an error
NoMethodError: private method `bar' called for #
from (irb):129
from :0

> foo.send(:bar)
You called bar
=> nil
m = foo.method(:bar)
=> #
> m.call
You called bar
=> nil
> foo.instance_eval { bar }
You called bar
=> nil


Remember you cannot use eval to call a private method:


> eval('foo.bar')
NoMethodError: private method `bar' called for #
from (irb):140
from (irb):140
from :0



Wednesday, 16 November 2011

How to become successful

This is a quite inspiring speech. Reaching a target or becoming successful takes time and pain. Rewards are difficult to obtain, but when you get it... it is awesome: