Swoole的HttpResponse对象有哪些常用方法

swoolehttpResponse对象用于发送HTTP响应,常用方法包括:1. header()设置响应头;2. status()修改状态码;3. cookie()写入Cookie;4. write()分段输出、end()结束响应;5. gzip()启用压缩;6. redirect()重定向;7. detach()和upgrade()用于websocket升级。需注意调用顺序与限制。

Swoole的HttpResponse对象有哪些常用方法

Swoole 的 HttpResponse 对象用于在 Swoole HTTP 服务器中向客户端发送响应。它封装了响应头、状态码、正文等信息,提供了多个实用方法来控制输出内容和行为。以下是常用的 HttpResponse 方法及其用途说明。

1. header() – 设置响应头

用于添加或修改 HTTP 响应头字段,比如 Content-Type、Cookie 等。

– 格式:header(String $key, string $value, bool $replace = true)
– 示例:
$response->header("Content-Type", "application/json");
$response->header("X-Powered-By", "Swoole");

注意:必须在 end() 之前调用,且不能重复设置相同键(除非 replace 为 true)。

2. status() – 设置 HTTP 状态码

自定义响应的 HTTP 状态码,如 404、500 等。

– 格式:status(int $code)
– 示例:
$response->status(404);
$response->status(500);

默认是 200,调用该方法可更改状态码。需在 end() 前设置。

3. cookie() – 设置 Cookie

向客户端写入 Cookie,支持设置路径、域、有效期等参数。

– 格式:cookie(string $name, string $value = '', int $expires = 0, string $path = "/", string $domain = "", bool $secure = false, bool $httponly = false)
– 示例:
header(string $key, string $value, bool $replace = true)0

常用于会话管理或用户识别。

4. write()end() – 输出响应内容

write() 用于分段输出内容,适用于大文件或流式传输;end() 结束响应并发送最终内容。

header(string $key, string $value, bool $replace = true)1:追加数据到响应体
header(string $key, string $value, bool $replace = true)2:结束响应,可带最后的数据

示例:

Swoole的HttpResponse对象有哪些常用方法

法语写作助手

法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。

Swoole的HttpResponse对象有哪些常用方法31

查看详情 Swoole的HttpResponse对象有哪些常用方法

header(string $key, string $value, bool $replace = true)3
header(string $key, string $value, bool $replace = true)4
header(string $key, string $value, bool $replace = true)5

使用 header(string $key, string $value, bool $replace = true)6 可实现 chunked 输出,end() 必须调用一次且只能一次。

5. gzip() – 启用 GZIP 压缩

对响应内容启用 GZIP 压缩,减少传输体积。

– 格式:header(string $key, string $value, bool $replace = true)8
– 示例:
header(string $key, string $value, bool $replace = true)9
$response->header("Content-Type", "application/json");0

客户端需支持 Accept-Encoding: gzip 才会生效。

6. redirect() – 重定向

发送 302 或其他类型的跳转响应。

– 格式:$response->header("Content-Type", "application/json");1
– 示例:
$response->header("Content-Type", "application/json");2

自动设置 location 头并结束响应。

7. detach() 和 upgrade() – 高级用法

detach() 将连接从当前请求分离,用于长连接或 WebSocket 升级前操作。
upgrade() 用于将 HTTP 连接升级为 WebSocket 连接。

– 常见于 WebSocket 服务中:
$response->header("Content-Type", "application/json");3

基本上就这些常用方法。掌握它们可以灵活控制 Swoole 中的 HTTP 响应行为,构建高性能 Web 服务或 API 接口时不复杂但容易忽略细节。

上一篇
下一篇
text=ZqhQzanResources