Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.DS_Store
.idea
test_marshaler.go
21 changes: 21 additions & 0 deletions api/grpc_gateway/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ var DefaultServeMuxOption = []runtime.ServeMuxOption{
runtime.WithErrorHandler(DefaultErrorHandler),
runtime.WithRoutingErrorHandler(DefaultRoutingErrorHandler),
runtime.WithIncomingHeaderMatcher(DefaultHeaderWarp),
// 标准 JSON 格式
runtime.WithMarshalerOption("application/json", &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
EmitUnpopulated: true,
UseProtoNames: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: false,
},
Comment on lines +31 to +33
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

DiscardUnknown: false 会拒绝包含未知字段的请求。

当设置为 false 时,如果请求 JSON 中包含 proto 定义中不存在的字段,反序列化将失败。这比默认行为更严格。

请确认这是预期行为。如果希望保持向前兼容性(允许客户端发送新字段而旧服务端忽略),建议设置为 true

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/grpc_gateway/mux.go` around lines 31 - 33, The protojson UnmarshalOptions
currently sets DiscardUnknown: false which causes JSON unmarshal to fail on
unknown fields; update the protojson.UnmarshalOptions used to configure the
HTTP->gRPC JSON parsing (the UnmarshalOptions block) to set DiscardUnknown: true
if you want forward-compatibility so new/unknown fields in requests are ignored,
or explicitly document/keep false if strict rejection of unknown fields is
intended; change the DiscardUnknown value on the UnmarshalOptions struct
accordingly.

}),
// Protobuf JSON 格式
runtime.WithMarshalerOption("application/jsonpb", &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
EmitUnpopulated: true,
Expand All @@ -31,6 +42,16 @@ var DefaultServeMuxOption = []runtime.ServeMuxOption{
DiscardUnknown: false,
},
}),
// 兜底方案:客户端没明确指定 Content-Type 时用这个
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
EmitUnpopulated: true,
UseProtoNames: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: false,
},
}),
}

func NewMixedPortServeMux(ctx context.Context, endpoint string, registers ...Register) (*runtime.ServeMux, error) {
Expand Down
Loading