Skip to content

响应转换器#

路由器中间件操作路由器特定的请求和响应对象,其主体是 []byte 切片或流。Huma 操作操作特定结构体实例。有时需要在操作处理程序运行 after 之后但在响应序列化为字节 before 之前,对结构化响应数据进行通用操作。这就是响应转换器的作用。

flowchart LR
	Request --> Middleware
	Middleware --> Unmarshal
	subgraph Huma
		Unmarshal --> Handler
		Handler --> Transformer
		Transformer --> Marshal
	end
	Marshal --> Response

	style Transformer stroke:#f9f,stroke-width:2px,stroke-dasharray: 5 5

响应转换器使您能够即时修改响应。例如,您可以向响应添加 Link 头,以指示响应主体由 JSON Schema 描述。这通过实现 huma.Transformer 接口并将其注册到 API 来完成。

一个简单的娱乐示例可能如下所示:

code.go
// FieldSelectTransform is an example of a transform that can use an input
// header value to modify the response on the server, providing a GraphQL-like
// way to send only the fields that the client wants over the wire.
func FieldSelectTransform(ctx Context, status string, v any) (any, error) {
	if fields := ctx.Header("Fields"); fields != "" {
		// Ugh this is inefficient... consider other ways of doing this :-(
		var tmp any
		b, _ := json.Marshal(v)
		json.Unmarshal(b, &tmp)
		result, _, err := shorthand.GetPath(fields, tmp, shorthand.GetOptions{})
		return result, err
	}
	return v, nil
}

可以使用如下方式:

Terminal
$ restish example.com/things/1 -H 'Fields: {id, tag_names: tags[].name}'

查看 huma.SchemaLinkTransformer 以获取更真实的深入示例。

深入了解#