Skip to content

流式传输#

响应 Body 可以是一个接受 huma.Context 的回调函数,以实现流式传输。huma.StreamResponse 实用工具使得返回此内容变得简单:

code.go
func handler(ctx context.Context, input *MyInput) (*huma.StreamResponse, error) {
	return &huma.StreamResponse{
		Body: func(ctx huma.Context) {
			// Write header info before streaming the body.
			ctx.SetHeader("Content-Type", "text/my-stream")
			writer := ctx.BodyWriter()

			// Update the write deadline to give us extra time.
			if d, ok := writer.(interface{ SetWriteDeadline(time.Time) error }); ok {
				d.SetWriteDeadline(time.Now().Add(5 * time.Second))
			} else {
				fmt.Println("warning: unable to set write deadline")
			}

			// Write the first message, then flush and wait.
			writer.Write([]byte("Hello, I'm streaming!"))
			if f, ok := writer.(http.Flusher); ok {
				f.Flush()
			} else {
				fmt.Println("error: unable to flush")
			}

			time.Sleep(3 * time.Second)

			// Write the second message.
			writer.Write([]byte("Hello, I'm still streaming!"))
		},
	}, nil
}

另请参阅 http.ResponseController,它可以用于设置超时、刷新等,通过一个简单的接口实现。

服务器发送事件

sse 包提供了一个用于流式传输服务器发送事件 (SSE) 响应的助手,比上面的示例更容易使用!

深入了解#