进阶 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,依此类推。

类型行为
stringbody
string, stringcontent-type, body
string, intbody, 状态码
int状态码
int, string状态码, body
error非 nil 时返回 bad request
any, bool为 false 时触发 404 Not Found
<Τ>JSON body
<Τ>, stringbody, content-type
<Τ>, errorJSON body 或 bad request
<Τ>, intJSON body, 状态码
Result调用其 Dispatch 方法
PreflightResult调用其 Preflight 方法

其中 <T> 表示任意 struct 值。

评论 (0)