|
6 | 6 | // $ php examples/59-server-json-api.php 8080 |
7 | 7 | // $ curl -v http://localhost:8080/ -H 'Content-Type: application/json' -d '{"name":"Alice"}' |
8 | 8 |
|
9 | | -use Psr\Http\Message\ServerRequestInterface; |
10 | 9 | use React\Http\Message\Response; |
11 | 10 |
|
12 | 11 | require __DIR__ . '/../vendor/autoload.php'; |
13 | 12 |
|
14 | | -$http = new React\Http\HttpServer(function (ServerRequestInterface $request) { |
| 13 | +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { |
15 | 14 | if ($request->getHeaderLine('Content-Type') !== 'application/json') { |
16 | | - return new Response( |
17 | | - Response::STATUS_UNSUPPORTED_MEDIA_TYPE, |
18 | | - array( |
19 | | - 'Content-Type' => 'application/json' |
20 | | - ), |
21 | | - json_encode(array('error' => 'Only supports application/json')) . "\n" |
22 | | - ); |
| 15 | + return Response::json( |
| 16 | + array('error' => 'Only supports application/json') |
| 17 | + )->withStatus(Response::STATUS_UNSUPPORTED_MEDIA_TYPE); |
23 | 18 | } |
24 | 19 |
|
25 | 20 | $input = json_decode($request->getBody()->getContents()); |
26 | 21 | if (json_last_error() !== JSON_ERROR_NONE) { |
27 | | - return new Response( |
28 | | - Response::STATUS_BAD_REQUEST, |
29 | | - array( |
30 | | - 'Content-Type' => 'application/json' |
31 | | - ), |
32 | | - json_encode(array('error' => 'Invalid JSON data given')) . "\n" |
33 | | - ); |
| 22 | + return Response::json( |
| 23 | + array('error' => 'Invalid JSON data given') |
| 24 | + )->withStatus(Response::STATUS_BAD_REQUEST); |
34 | 25 | } |
35 | 26 |
|
36 | 27 | if (!isset($input->name) || !is_string($input->name)) { |
37 | | - return new Response( |
38 | | - Response::STATUS_UNPROCESSABLE_ENTITY, |
39 | | - array( |
40 | | - 'Content-Type' => 'application/json' |
41 | | - ), |
42 | | - json_encode(array('error' => 'JSON data does not contain a string "name" property')) . "\n" |
43 | | - ); |
| 28 | + return Response::json( |
| 29 | + array('error' => 'JSON data does not contain a string "name" property') |
| 30 | + )->withStatus(Response::STATUS_UNPROCESSABLE_ENTITY); |
44 | 31 | } |
45 | 32 |
|
46 | | - return new Response( |
47 | | - Response::STATUS_OK, |
48 | | - array( |
49 | | - 'Content-Type' => 'application/json' |
50 | | - ), |
51 | | - json_encode(array('message' => 'Hello ' . $input->name)) . "\n" |
| 33 | + return Response::json( |
| 34 | + array('message' => 'Hello ' . $input->name) |
52 | 35 | ); |
53 | 36 | }); |
54 | 37 |
|
|
0 commit comments