swoole-framwork/core/http/Response.php

61 lines
1.5 KiB
PHP
Raw Normal View History

2024-05-20 11:51:07 +08:00
<?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'];
$res = $this->getBody();
if (in_array(gettype($res), $jsonConver)) {
$this->swooleResponse->header("Content-type","application/json;charset=utf-8");
$res = json_encode($res, 256);
}
$this->swooleResponse->write($res);
$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);
}
}