swoole-framwork/core/http/Response.php

65 lines
1.7 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()
{
2024-05-21 14:33:56 +08:00
$jsonConver = ['array', 'object'];
$body = $this->getBody();
if (in_array(gettype($body), $jsonConver)) {
2024-05-20 11:51:07 +08:00
$this->swooleResponse->header("Content-type","application/json;charset=utf-8");
2024-05-21 14:33:56 +08:00
$res = json_encode($body, 256);
$this->swooleResponse->write($res);
}else{
if ($body) {
$this->swooleResponse->write($body);
}
2024-05-20 11:51:07 +08:00
}
$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);
}
}