http_response 字段和方法
由控制器和中间件生成的响应:@response()、@view()、@redirect()。
字段是关于值的一个普通事实,用点号读取,不需要方括号:$value.name。方法会接收参数或执行操作,调用方式为 ->:$value->name(arguments),也可以把值通过管道传入:$value |> name(arguments)。
字段
| 字段 | 类型 | 说明 |
|---|
.body | string | 以文本形式表示的响应体。 |
.is_ok | bool | 状态码为 2xx 时为 true。 |
.status | number | HTTP 状态码,如 200 或 404。 |
.type | string | Content-Type。 |
来自 KScript.Http
这些需要 <import package="KScript.Http" />import KScript.Http。参见 KScript.Http。
设置 Cache-Control:->with_cache('public, max-age=300'),或以秒数设置:->with_cache(300)。
示例
<fn name="index" params="request">
<return value="@view('posts/index')->with_cache(300)" />
</fn>
fn index(request) {
return @view('posts/index')->with_cache(300)
}
#http_response->with_cookie(name, value, expires?: duration, path?, domain?, http_only?: bool, secure?: bool, same_site?: lax|strict|none) → http_response KScript.Http
设置一个 cookie 并返回该响应。除非另行指定,cookie 默认为 HttpOnly 和 SameSite=Lax;在 https 下为 Secure;有效期为浏览器会话,除非给出 expires:(如 30d)。
| 参数 | 接受 |
|---|
name 必填 | 任意值 |
value required | 任意值 |
expires 可选 | duration |
path 可选 | 任意值 |
domain 可选 | 任意值 |
http_only 可选 | 标志:http_only 或 not http_only |
secure 可选 | 标志:secure 或 not secure |
same_site 可选 | 以下单词之一:lax|strict|none |
参数可以命名:->with_cookie(…, value: …, expires: …)。
示例
<fn name="remember_theme" params="request">
<return value="@redirect('/')->with_cookie('theme', 'dark', expires: 30d)" />
</fn>
fn remember_theme(request) {
return @redirect('/')->with_cookie('theme', 'dark', expires: 30d)
}
设置 ETag:取值的哈希,或取无 ETag 时正文的哈希。添加 etag 中间件(或 etag="true")即可用 304 响应 If-None-Match。
| 参数 | 接受 |
|---|
value 可选 | 任意值 |
weak 可选 | 标志:weak 或 not weak |
参数可以命名:->with_etag(…, weak: …)。
示例
<fn name="show" params="request">
<return value="@response({ id: 1, title: 'Hello' })->with_etag()" />
</fn>
fn show(request) {
return @response({ id: 1, title: 'Hello' })->with_etag()
}
更改状态码并返回响应。
示例
<fn name="store" params="request">
<return value="@response({ saved: true })->with_status(201)" />
</fn>
fn store(request) {
return @response({ saved: true })->with_status(201)
}
更改 Content-Type 并返回响应。
示例
<fn name="export" params="request">
<return value="@response('name,email')->with_type('text/csv')" />
</fn>
fn export(request) {
return @response('name,email')->with_type('text/csv')
}
#http_response->without_cookie(name, path?, domain?) → http_response KScript.Http
让浏览器删除一个 Cookie 并返回响应。请提供设置该 Cookie 时所用的路径和域名。
参数可以命名:->without_cookie(…, path: …, domain: …)。
示例
<fn name="forget_theme" params="request">
<return value="@redirect('/')->without_cookie('theme')" />
</fn>
fn forget_theme(request) {
return @redirect('/')->without_cookie('theme')
}
来自 any 的方法