Response Writer Extension

Hertz provides response writer extension, if users need to hijack the writer of the response, they can implement the corresponding interfaces according to their needs.

Interface Definition

interface is defined in pkg/network/writer.

type ExtWriter interface {
	io.Writer
	Flush() error

	// Finalize will be called by framework before the writer is released.
	// Implementations must guarantee that Finalize is safe for multiple calls.
	Finalize() error
}

Hijack Your Own Response Writer

Hertz provides Response.HijackWriter in app.RequestContext to allow users to hijack their own response writer, which provides another way for response writing process.

Example:

	h.GET("/hijack", func(c context.Context, ctx *app.RequestContext) {
		// Hijack the writer of response
		ctx.Response.HijackWriter(yourResponseWriter)
	}

Supported Response Writer Extension

Hertz provides NewChunkedBodyWriter to create a response writer which allow users to flush chunk immediately during the handler process, it is defined under pkg/protocol/http1/resp/writer, and you can implement your own response writer.

ChunkedBodyWriter

Example:

	h.GET("/flush/chunk", func(c context.Context, ctx *app.RequestContext) {
		// Hijack the writer of response
		ctx.Response.HijackWriter(resp.NewChunkedBodyWriter(&ctx.Response, ctx.GetWriter()))

		for i := 0; i < 10; i++ {
			ctx.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck
			ctx.Flush()                                                                 // nolint: errcheck
			time.Sleep(200 * time.Millisecond)
		}
	})

Last modified July 30, 2023 : fix type error (#735) (50c91bf)