Skip to content

Commit eb00df8

Browse files
authored
Merge pull request #39 from hduhelp/fix/content-type-marshaler
fix(grpc-gateway): support application/json and wildcard marshaler in ServeMux
2 parents ef01eb4 + 49083c7 commit eb00df8

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
.DS_Store
22
.idea
3+
test_marshaler.go

api/grpc_gateway/mux.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ var DefaultServeMuxOption = []runtime.ServeMuxOption{
2222
runtime.WithErrorHandler(DefaultErrorHandler),
2323
runtime.WithRoutingErrorHandler(DefaultRoutingErrorHandler),
2424
runtime.WithIncomingHeaderMatcher(DefaultHeaderWarp),
25+
// 标准 JSON 格式
26+
runtime.WithMarshalerOption("application/json", &runtime.JSONPb{
27+
MarshalOptions: protojson.MarshalOptions{
28+
EmitUnpopulated: true,
29+
UseProtoNames: true,
30+
},
31+
UnmarshalOptions: protojson.UnmarshalOptions{
32+
DiscardUnknown: false,
33+
},
34+
}),
35+
// Protobuf JSON 格式
2536
runtime.WithMarshalerOption("application/jsonpb", &runtime.JSONPb{
2637
MarshalOptions: protojson.MarshalOptions{
2738
EmitUnpopulated: true,
@@ -31,6 +42,16 @@ var DefaultServeMuxOption = []runtime.ServeMuxOption{
3142
DiscardUnknown: false,
3243
},
3344
}),
45+
// 兜底方案:客户端没明确指定 Content-Type 时用这个
46+
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
47+
MarshalOptions: protojson.MarshalOptions{
48+
EmitUnpopulated: true,
49+
UseProtoNames: true,
50+
},
51+
UnmarshalOptions: protojson.UnmarshalOptions{
52+
DiscardUnknown: false,
53+
},
54+
}),
3455
}
3556

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

0 commit comments

Comments
 (0)