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)
- Kratos middleware seems to only apply to unary gRPC operations HOT 7
- t
- [Question] About the current p2c algorithm HOT 1
- bug in Quick Start HOT 1
- [Question]how can i catch issue when i use config hot reload with a mismatch type
- 使用北极星作为服务发现时,在注册多个grpc client时,启动报错:concurrent map iteration and map write HOT 4
- [Question]how to get all router HOT 1
- GRPC MaxSendMsgSize MaxRecvMsgSize setting HOT 1
- [Question] Error: no_available_node HOT 13
- [Question] After creating a new service, the grpc test is normal, but when requesting bff through http, the bff layer does not initiate a grpc call to the business layer and returns DeadlineExceeded. Which part should be checked? HOT 1
- Whitelist: selector middleware doesn't work for grpc HOT 1
- [Question] Next release date for kratos? HOT 1
- kratos proto client api/helloworld/v2 fail? HOT 1
- [Question] HOT 2
- [Feature]go-kratos 的ResponseEncoder 可以根据不同的路由,设置不同的encoder吗 HOT 2
- [Feature] Add convenient functions to return official codec in encoding package. HOT 5
- [Question] Whether the k8s Headless service supports namespaces HOT 1
- kratos new helloworld - does not work
- [Question] How to define 4xx, 5xx response codes in openapi spec generate from proto definitions HOT 1
- [Question]In the streaming mode of grpc, docking with jwt failed HOT 5
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.