65 lines
1.7 KiB
PHP
65 lines
1.7 KiB
PHP
<?php
|
|
namespace Core\http;
|
|
|
|
class Response
|
|
{
|
|
/**
|
|
* @var \Swoole\Http\Response
|
|
*/
|
|
protected $swooleResponse;
|
|
protected $body;
|
|
|
|
public function __construct($swooleResponse)
|
|
{
|
|
$this->swooleResponse = $swooleResponse;
|
|
$this->_setHeader("Content-Type","text/plain;charset=utf-8");
|
|
}
|
|
private function _setHeader($key,$value)
|
|
{
|
|
$this->swooleResponse->header($key,$value);
|
|
}
|
|
|
|
public function writeHttpStatus(int $code)
|
|
{
|
|
$this->swooleResponse->status($code);
|
|
}
|
|
|
|
public function end()
|
|
{
|
|
$jsonConver = ['array', 'object'];
|
|
$body = $this->getBody();
|
|
if (in_array(gettype($body), $jsonConver)) {
|
|
$this->swooleResponse->header("Content-type","application/json;charset=utf-8");
|
|
$res = json_encode($body, 256);
|
|
$this->swooleResponse->write($res);
|
|
}else{
|
|
if ($body) {
|
|
$this->swooleResponse->write($body);
|
|
}
|
|
}
|
|
$this->swooleResponse->end();
|
|
}
|
|
|
|
public function writeRedirect(string $url,int $code=302)
|
|
{
|
|
$this->swooleResponse->redirect($url,$code); //此方法跳转后服务器会报错
|
|
//Warning: Swoole\Http\Response::header(): Http request is finished. in /pro/pro/core/http/Response.php on line 59
|
|
//$this->writeHttpStatus($code);
|
|
//$this->_setHeader("Location",$url);
|
|
}
|
|
|
|
public function getBody()
|
|
{
|
|
return $this->body;
|
|
}
|
|
|
|
public function setBody($body)
|
|
{
|
|
$this->body = $body;
|
|
}
|
|
|
|
public static function init(\Swoole\Http\Response $response)
|
|
{
|
|
return new self($response);
|
|
}
|
|
} |