Advertisement
dev017

Http with perl

Jul 30th, 2023
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.61 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. use HTTP::Daemon;
  4. use HTTP::Status;
  5. use JSON;
  6.  
  7. my $httpd = HTTP::Daemon->new(
  8.     LocalAddr => 'localhost',
  9.     LocalPort => 3000,
  10. ) or die "não foi possível iniciar o servidor: $!\n";
  11.  
  12. my @coins;
  13.  
  14. print "servidor rodando em http://localhost:3000\n";
  15.  
  16. while (my $client = $httpd->accept) {
  17.     while (my $request = $client->get_request) {
  18.         if ($request->method eq 'POST' && $request->url->path eq '/add') {
  19.             my $content = $request->content;
  20.             my $coin = decode_json($content);
  21.             push @coins, $coin;
  22.             $client->send_response(
  23.                 HTTP::Response->new(
  24.                     HTTP_OK,
  25.                     undef,
  26.                     [ 'Content-Type' => 'application/json' ],
  27.                     encode_json({ message => 'moeda adicionada com sucesso' })
  28.                 )
  29.             );
  30.         } elsif ($request->method eq 'GET' && $request->url->path eq '/coins') {
  31.             $client->send_response(
  32.                 HTTP::Response->new(
  33.                     HTTP_OK,
  34.                     undef,
  35.                     [ 'Content-Type' => 'application/json' ],
  36.                     encode_json(\@coins)
  37.                 )
  38.             );
  39.         } else {
  40.             $client->send_response(
  41.                 HTTP::Response->new(
  42.                     HTTP_NOT_FOUND,
  43.                     undef,
  44.                     [ 'Content-Type' => 'application/json' ],
  45.                     encode_json({ message => 'endpoint não encontrado' })
  46.                 )
  47.             );
  48.         }
  49.     }
  50.     $client->close;
  51.     undef $client;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement