forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
59-server-json-api.php
58 lines (49 loc) · 1.87 KB
/
59-server-json-api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
// Simple JSON-based HTTP API example as a base to build RESTful/RESTish APIs
// Launch demo and use your favorite CLI tool to test API requests
//
// $ php examples/59-server-json-api.php 8080
// $ curl -v http://localhost:8080/ -H 'Content-Type: application/json' -d '{"name":"Alice"}'
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
require __DIR__ . '/../vendor/autoload.php';
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
if ($request->getHeaderLine('Content-Type') !== 'application/json') {
return new Response(
415, // Unsupported Media Type
array(
'Content-Type' => 'application/json'
),
json_encode(array('error' => 'Only supports application/json')) . "\n"
);
}
$input = json_decode($request->getBody()->getContents());
if (json_last_error() !== JSON_ERROR_NONE) {
return new Response(
400, // Bad Request
array(
'Content-Type' => 'application/json'
),
json_encode(array('error' => 'Invalid JSON data given')) . "\n"
);
}
if (!isset($input->name) || !is_string($input->name)) {
return new Response(
422, // Unprocessable Entity
array(
'Content-Type' => 'application/json'
),
json_encode(array('error' => 'JSON data does not contain a string "name" property')) . "\n"
);
}
return new Response(
200,
array(
'Content-Type' => 'application/json'
),
json_encode(array('message' => 'Hello ' . $input->name)) . "\n"
);
});
$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0');
$http->listen($socket);
echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;