Skip to content

自动修补#

如果同一个资源存在 GETPUT,但服务器启动时不存在 PATCH,则可以为您生成 PATCH 操作,以使客户端的编辑更方便。您可以通过 autopatch 包选择启用此行为:

import "github.com/danielgtaylor/huma/v2/autopatch"

// ...

// Later in the code *after* registering operations...
autopatch.AutoPatch(api)

如果 GET 返回 ETagLast-Modified 头,则这些头将用于 PUT 操作的条件请求,以防止分布式写入冲突,从而避免覆盖其他人的更改。

以下格式开箱即用,通过 Content-Type 头选择:

Merge 的增强版

您可以将 Shorthand Merge Patch 视为 JSON 合并补丁的扩展,支持字段路径、数组以及其他一些功能。这样的补丁是可能的,例如将项追加到数组(如果需要则创建它):

{
	foo.bar[]: "baz",
}

如果 PATCH 请求没有 Content-Type 头,或者使用 application/json 或其变体,则假设为 JSON Merge Patch。

禁用自动修补#

可以通过在操作上设置元数据来为每个资源禁用自动修补功能:

code.go
// Register an operation that won't get a PATCH generated.
huma.Register(api, huma.Operation{
	OperationID: "get-greeting",
	Method:      http.MethodGet,
	Path:        "/greeting/{name}",
	Summary:     "Get a greeting",
	Metadata: map[string]interface{}{
		"autopatch": false,
	},
}, func(ctx context.Context, input *GreetingInput) (*GreetingOutput, error) {
	// ...
})

深入了解#