Http调用模式
<?php
use RingCentral\Psr7\Response;
function handler($request, $context): Response{
$body = $request->getBody()->getContents();
$queries = $request->getQueryParams();
$method = $request->getMethod();
$headers = $request->getHeaders();
$path = $request->getAttribute('path');
$requestURI = $request->getAttribute('requestURI');
$clientIP = $request->getAttribute('clientIP');
$_SERVER['REQUEST_METHOD'] = $method;
$_SERVER['REQUEST_URI'] = $requestURI;
$_SERVER['REMOTE_ADDR'] = $clientIP;
$_SERVER['CONTENT_TYPE'] = $headers['Content-Type'][0];
$_POST = [];
if (strpos($_SERVER['CONTENT_TYPE'], 'application/x-www-form-urlencoded') !== false) {
mb_parse_str(urldecode($body), $_POST);
} elseif (strpos($_SERVER['CONTENT_TYPE'], 'multipart/form-data') !== false) {
parse_raw_http_request($_SERVER['CONTENT_TYPE'], $body, $_POST);
} else {
$_POST = json_decode($body, true);
}
$_GET = $queries;
$_POST = empty($_POST) ? [] : $_POST;
$_REQUEST = array_merge($_GET, $_POST);
//处理自己的代码
//返回结果给用户端,需要自行处理状态和返回格式
$respHeaders = array('Content-Type' => 'application/json');
$respBody = json_encode($_SERVER);
return new Response(200, $respHeaders, $respBody);
}
function parse_raw_http_request($content_type, $input, array &$a_data)
{
preg_match('/boundary=(.*)$/', $content_type, $matches);
$boundary = $matches[1];
$a_blocks = preg_split("/-+$boundary/", $input);
array_pop($a_blocks);
foreach ($a_blocks as $id => $block) {
if (empty($block)) {
continue;
}
if (strpos($block, 'application/octet-stream') !== false) {
preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches);
} else {
preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
}
if (!empty($matches[1]) && !empty($matches[2])) {
// print_r($matches);
$a_data[$matches[1]] = $matches[2];
}
}
}
?>