Skip to content

Commit eab47b5

Browse files
authored
fix: check obj type in protobufBinding (#2851)
* fix: check obj type in protobufBinding * fix: UnitTest for invalid proto obj
1 parent deb83b6 commit eab47b5

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

binding/binding_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1339,6 +1339,13 @@ func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body
13391339
err := b.Bind(req, &obj)
13401340
assert.Error(t, err)
13411341

1342+
invalid_obj := FooStruct{}
1343+
req.Body = ioutil.NopCloser(strings.NewReader(`{"msg":"hello"}`))
1344+
req.Header.Add("Content-Type", MIMEPROTOBUF)
1345+
err = b.Bind(req, &invalid_obj)
1346+
assert.Error(t, err)
1347+
assert.Equal(t, err.Error(), "obj is not ProtoMessage")
1348+
13421349
obj = protoexample.Test{}
13431350
req = requestWithBody("POST", badPath, badBody)
13441351
req.Header.Add("Content-Type", MIMEPROTOBUF)

binding/protobuf.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package binding
66

77
import (
8+
"errors"
89
"io/ioutil"
910
"net/http"
1011

@@ -26,7 +27,11 @@ func (b protobufBinding) Bind(req *http.Request, obj interface{}) error {
2627
}
2728

2829
func (protobufBinding) BindBody(body []byte, obj interface{}) error {
29-
if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil {
30+
msg, ok := obj.(proto.Message)
31+
if !ok {
32+
return errors.New("obj is not ProtoMessage")
33+
}
34+
if err := proto.Unmarshal(body, msg); err != nil {
3035
return err
3136
}
3237
// Here it's same to return validate(obj), but util now we can't add

0 commit comments

Comments
 (0)