#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;

use HTTP::Request;
use LWP::UserAgent;
use WWW::Curl::Simple;
use Encode;

#use constant URL => "http://validator.nu/?out=json";
use constant URL => "http://html5.validator.nu/?out=json";


my $data = "";
while(<STDIN>) { $data .= $_; }

sub create_request {
    my $data = shift;
    my $request = HTTP::Request->new(POST => URL);
    $request->header ('Content-Type', 'text/html; charset=UTF-8');
    $request->content (encode ("utf-8", $data));
    return $request
}

sub post_length { say "\tPOST with length ", length shift , " to ", URL; }
sub response_length { say "\tlength of response: ", length shift; }
sub response_tail   { say "\t...", substr(shift, -68); }

sub handle_response {
    my $response = shift;
    response_length $response;
    response_tail $response;
}

sub post_lwp {
    my $request = create_request $data;
    my $ua = LWP::UserAgent->new(timeout => 10);
    $ua->timeout (10);
    post_length $request->content;
    my $response = $ua->request($request);
    handle_response $response->content;
}

sub post_curl {
    my $request = create_request $data;
    my $curl = WWW::Curl::Simple->new(timeout => 10);
    my $response_body;
    post_length $data;
    my $response = $curl->request($request);
    handle_response $response->content;
    #say $response->content;
}


say "";
say "trying Curl:";
post_curl;
say "trying LWP:";
post_lwp;
