进阶 www.iris-go.com 2026-10-20 02:39:14 · 21 阅读
第5章 API 返回值与响应行为解析
输出
如果返回值是 string,它会作为响应的 body 发送。如果是 int,则会作为状态码发送。如果是 error,会返回 bad request 并把该错误作为原因。如果同时是 error 和 int,则状态码使用该整数而不是 400(bad request)。如果是自定义 struct,且尚未设置 Content-Type 头,则将其序列化为 JSON 发送。如果是自定义 struct 加 string,则第二个返回值 string 会作为 Content-Type,依此类推。
| 类型 | 行为 |
|---|---|
| string | body |
| string, string | content-type, body |
| string, int | body, 状态码 |
| int | 状态码 |
| int, string | 状态码, body |
| error | 非 nil 时返回 bad request |
| any, bool | 为 false 时触发 404 Not Found |
| <Τ> | JSON body |
| <Τ>, string | body, content-type |
| <Τ>, error | JSON body 或 bad request |
| <Τ>, int | JSON body, 状态码 |
| Result | 调用其 Dispatch 方法 |
| PreflightResult | 调用其 Preflight 方法 |
其中 <T> 表示任意 struct 值。