-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Closed
Labels
Description
Please see the FAQ in our main README.md before submitting your issue.
What problem is the feature used to solve?
Go added a new feature called NewResponseController in go 1.20. Pay attention to the doc blow:
The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter.
As it said, custom ResponseWriter should add an Unwrap method to return underlaying ResponseWriter.
Currently, there is a custom ResponseWriter in transport/http. And it is used in http.Context:
kratos/transport/http/context.go
Lines 45 to 66 in 3110168
type responseWriter struct { | |
code int | |
w http.ResponseWriter | |
} | |
func (w *responseWriter) reset(res http.ResponseWriter) { | |
w.w = res | |
w.code = http.StatusOK | |
} | |
func (w *responseWriter) Header() http.Header { return w.w.Header() } | |
func (w *responseWriter) WriteHeader(statusCode int) { w.code = statusCode } | |
func (w *responseWriter) Write(data []byte) (int, error) { | |
w.w.WriteHeader(w.code) | |
return w.w.Write(data) | |
} | |
type wrapper struct { | |
router *Router | |
req *http.Request | |
res http.ResponseWriter | |
w responseWriter | |
} |
Shall we support this feature, so that we can use some code likes below:
_ = http.NewServer(
http.ResponseEncoder(func(w http.ResponseWriter, r *http.Request, i any) error {
rc := nt.NewResponseController(w)
bs, _ := encoding.GetCodec("json").Marshal(i)
n := len(bs) / 2
n, _ = w.Write(bs[:n]) // 1. write half of the response
_ = rc.Flush() // 2. flush response first
_, err := w.Write(bs[n:]) // 3. write the rest
return err
}),
)
Requirements description of the feature
Add an "Unwrap" method to transport/http.responseWriter.
func (w *responseWriter) Unwrap() http.ResponseWriter { return w.w }