Comments (4)
🤖
It's great that you've identified a potential improvement in the http.wrapper.Result()
method. Your understanding of the code and the proposed change seem well-reasoned. If you believe this change would benefit the project, I encourage you to create a pull request with your proposed modification. Your contribution could help improve the project for everyone. Thank you for considering to contribute!
This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.
Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.
If you want to continue the conversation, start your reply with @dosu-bot.
from kratos.
我看完源码后猜测可能是因为这个原因:
-
仔细看 responseWriter 类型的方法,它实现了一个类似于“缓存响应码”的功能。
kratos/transport/http/context.go
Lines 55 to 59 in a556a2b
-
这是 Result 方法,可以看到和其他方法相比,如 "JSON",它缺少了设置 "Content-Type" 响应头的步骤,直接设置了响应码。
kratos/transport/http/context.go
Lines 110 to 119 in a556a2b
-
在默认的 enc 函数中操作了 header,根据数据类型添加了对应响应头。
kratos/transport/http/codec.go
Line 98 in a556a2b
-
go 源码中 ResponseWriter 的 Header 的注释中说了,设置了响应码之后,Header 的更改就无效了。
https://github.com/golang/go/blob/f719d5cffdb8298eff7a5ef533fe95290e8c869c/src/net/http/server.go#L99-L101
所以我推测,是因为必须在 Result 等方法中先设置响应码。而先设置响应码会导致响应头的修改无效。所以才有了 responseWriter。不过不论如何,这里肯定有问题就是了,起码 c.res 和 c.w 不应该同时存在。
from kratos.
Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑🤝🧑👫🧑🏿🤝🧑🏻👩🏾🤝👨🏿👬🏿
After reading the source code, I guessed it might be because of this:
-
Look carefully at the method of the responseWriter type. It implements a function similar to "caching response codes".
kratos/transport/http/context.go
Lines 55 to 59 in a556a2b
-
This is the Result method. You can see that compared with other methods, such as "JSON", it lacks the step of setting the "Content-Type" response header and directly sets the response code.
kratos/transport/http/context.go
Lines 110 to 113 in a556a2b
-
The header is operated in the default enc function and the corresponding response header is added according to the data type.
kratos/transport/http/codec.go
Line 98 in a556a2b
-
The comments on the Header of ResponseWriter in the go source code say that after the response code is set, changes to the Header will be invalid.
https://github.com/golang/go/blob/f719d5cffdb8298eff7a5ef533fe95290e8c869c/src/net/http/server.go#L99-L101
So I speculate that it is because the response code must be set first in methods such as Result. Setting the response code first will cause the modification of the response header to be invalid. That's why there is responseWriter. But no matter what, there must be a problem here. At least c.res and c.w should not exist at the same time.
from kratos.
@xbchaos Use can use the code below when kratos version >= v2.7.3 to get the underlying custom writer that you've set before:
If you think this code can solve your problem, remember to close this issue.
PR reference: #3265
package main
import (
"context"
"fmt"
"io"
nt "net/http"
"net/http/httptest"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport/http"
)
type customWriter struct {
http.ResponseWriter
}
func main() {
s := http.NewServer(
http.Middleware(func(h middleware.Handler) middleware.Handler {
return func(ctx context.Context, req any) (any, error) {
hc := ctx.(http.Context)
hc.Reset(customWriter{hc.Response()}, hc.Request()) // reset response writer
return h(ctx, req)
}
}),
http.ResponseEncoder(func(w http.ResponseWriter, r *http.Request, v any) error {
// get underlying response writer
var ok bool
under := w
out:
for {
switch cur := under.(type) {
case customWriter:
under = cur
ok = true
break out
case interface{ Unwrap() http.ResponseWriter }:
under = cur.Unwrap()
default:
break out
}
}
return http.DefaultResponseEncoder(w, r, ok)
}),
)
// simulate what happened in xx_http.pb.go
s.Route("/").GET("/a", func(ctx http.Context) error {
h := ctx.Middleware(func(ctx context.Context, req any) (any, error) {
return nil, nil
})
out, _ := h(ctx, nil)
return ctx.Result(200, out)
})
w := httptest.NewRecorder()
r := httptest.NewRequest(nt.MethodGet, "/a", nil)
s.ServeHTTP(w, r)
res := w.Result()
defer res.Body.Close()
bs, _ := io.ReadAll(res.Body)
fmt.Println(string(bs)) // true
}
from kratos.
Related Issues (20)
- [Feature] consule register need suport tags[] HOT 2
- When the App stops, the ctx in the afterStop callback is not available HOT 3
- [Question] How to return other Status Code in a successful HTTP request? HOT 7
- [Feature] Add Unwrap to custom response writer. HOT 3
- [Proposal] config feature roadmap HOT 22
- [Feature] replace kratos metrics with otel metrics HOT 3
- [The modification of header file information of http response does not take effect] ctx.Header().Set("Content-Type", "application/octet-stream") HOT 5
- [Question] How to return a custom response json? HOT 1
- Package version dependency issue HOT 4
- go generate ./...failed HOT 5
- [Feature]Add svrType related fields in proto to protoc-gen-go-http and http transport HOT 3
- proto file used to build the api document reported an error HOT 1
- consul watch, the server is offline and will not receive any notification HOT 6
- [Feature] Add NewClient method to gRPC Client HOT 3
- [Question] DDD的最佳实践方式?包括CQRS、Clean Architecture、六边形结构 HOT 5
- [Question]请教下kratos如何定义支持上传文件接口? HOT 2
- metrics statistics and usage issues [Question] HOT 5
- `stream` response in proto failed to generate http client HOT 6
- [Feature] Add kratos errors to buf remote plugin HOT 1
- [Question] I modified it based on examples/helloworld and found that client/main.go reported an error when executing. I am not sure if it is a BUG. HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from kratos.