Skip to content

请求限制#

截止期限与超时#

服务器和请求上下文的组合可用于控制截止期限与超时。Go 内置的 HTTP 服务器支持一些超时设置:

code.go
srv := &http.Server{
	ReadTimeout:       5 * time.Second,
	WriteTimeout:      5 * time.Second,
	IdleTimeout:       30 * time.Second,
	ReadHeaderTimeout: 2 * time.Second,
	// ...
}

Huma 请求上下文(通过解析器访问)可用于设置读取截止期限,这可用于处理大型或流式输入:

code.go
type MyInput struct {}

func (m *MyInput) Resolve(ctx huma.Context) []error {
	ctx.SetReadDeadline(time.Now().Add(5 * time.Second))
}

此外,可以使用 context.Context 为数据库等依赖项设置截止期限:

code.go
// Create a new context with a 10 second timeout.
newCtx, cancel := context.WithTimeout(ctx, 10 * time.Second)
defer cancel()

// Use the new context for any dependencies.
result, err := myDB.Get(newCtx, /* ... */)
if err != nil {
	// Deadline may have been hit, handle it here!
}

体大小限制#

默认情况下,每个操作的请求体大小限制为 1 MiB。可以更改此限制,通过在注册操作时将 huma.Operation.MaxBodyBytes 设置为不同的值。如果请求体大于限制,则将返回 413 Request Entity Too Large 错误。

code.go
huma.Register(api, huma.Operation{
	OperationID:  "put-thing",
	Method:       http.MethodPut,
	Path:         "/things/{thing-id}",
	Summary:      "Put a thing by ID",
	MaxBodyBytes: 10 * 1024 * 1024, // 10 MiB
}, func(ctx context.Context, input ThingRequest) (*struct{}, error) {
	// Do nothing...
	return nil, nil
}

请记住,在传递给处理函数之前,体会被读取到内存中。

深入了解#