适用于同一个端,不同服务器接口为了统一同一域名
public function handle(){
$request = request();
$curl = new Curl();
//设置header头
$headers['stresstest'] = 'l3KRU7Cwu8kVcqif';
$headers['token'] = 'WpNb7lBkoI1y5mUt';
$headers['manager_id'] = $this->userInfo['id'] ?? 0;
$headers['manager_name'] = $this->userInfo['username'] ?? '';
foreach ($headers as $key => $value) {
$curl->setHeader($key, $value);
}
//body
$body = $request->{$request->method()}();
//url
$url = trim($request->url(), '/');
$host = trim(config('insurance.url'), '/');
//替换转发路径
$url = $host . '/' .$this->module($url);
$url .= stripos($url, '?') === false ? "?" : "&";
$url .= "manage_id={$headers['manager_id']}&manage_name={$headers['manager_name']}";
//var_dump($url);die;//
//传输文件
foreach ((array)$request->file() as $key => $file) {
$body[$key] = new \CURLFile($file->getInfo()['tmp_name'],$file->getMime(),$file->getInfo()['name']);
$hasFile = true;
}
//请求内容类型
$contentType = $request->header('content-type');
$version = $request->header('version');
//发起请求
$method = strtolower($request->method());
//如果有文件时,不要设置content-type,没有文件时由客户端决定content-type
if (!isset($hasFile)) { $curl->setHeader('content-type', $contentType); }
//传递版本信息
$curl->setHeader('version', $version);
//如果content-type是json,设置payload标记为true,并encode body
$payload = false;
if (stripos($contentType, 'application/json') !== false) {
$payload = true;
//对象需要json_encode
if($method =='put' || $method =='delete'){
$body = json_encode($body);
}
}
if($method=='get'){ $body= []; }
Log::info('url:'.$url.'method:'.$method.'body:'.json_encode($body).'payload:'.json_encode($payload));
call_user_func_array([$curl, $method], [$url, $body, $payload]);
//设置响应头
foreach ($curl->response_headers as $header) { header($header); }
//输出内容
echo $curl->response; die;
//return json_decode($curl->response);
}
/**
* 路由替换
* [@param](https://my.oschina.net/u/2303379) $url
* [@return](https://my.oschina.net/u/556800) mixed
*/
protected function module($url)
{
//待转发 去 的 请求
$paths = [
// 'insure/order-list', 'insure/order-detail', 'insure/order-list-export', // 'insure/order-statistics', 'insure/order-channel-statistics-export', 'insure/zc-channel-list', // 'insure/invoice-list','insure/invoice-update','insure/invoice-export', ];
//地址文本
$reqPath = trim(request()->path(), '/');
//地址分段数组
$reqPathArr = explode('/',$reqPath);
//默认待删除根路径
$yzcRoot = 'insure';
//默认跳转 运营端
$classRoot = 'insure';
//待转发请求 在设置数组内 则跳转 运营端
if (in_array( $reqPath , $paths)) {$classRoot = 'insure'; }
//二级地址 有 module 则 跳转
if( isset($reqPathArr[1]) && $reqPathArr[1]=='module' ){
//待删除根路径
$yzcRoot = 'insure/module'; $classRoot = '';
}
$url = str_replace($yzcRoot, $classRoot, $url);
$url = trim($url,'/');
return $url;
}