Skip to content

Commit

Permalink
fix: check obj type in protobufBinding (gin-gonic#2851)
Browse files Browse the repository at this point in the history
* fix: check obj type in protobufBinding

* fix: UnitTest for invalid proto obj
  • Loading branch information
Tevic authored and daheige committed Apr 18, 2022
1 parent 78c3bc4 commit 15427d3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
7 changes: 7 additions & 0 deletions binding/binding_test.go
Expand Up @@ -1339,6 +1339,13 @@ func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body
err := b.Bind(req, &obj)
assert.Error(t, err)

invalid_obj := FooStruct{}
req.Body = ioutil.NopCloser(strings.NewReader(`{"msg":"hello"}`))
req.Header.Add("Content-Type", MIMEPROTOBUF)
err = b.Bind(req, &invalid_obj)
assert.Error(t, err)
assert.Equal(t, err.Error(), "obj is not ProtoMessage")

obj = protoexample.Test{}
req = requestWithBody("POST", badPath, badBody)
req.Header.Add("Content-Type", MIMEPROTOBUF)
Expand Down
7 changes: 6 additions & 1 deletion binding/protobuf.go
Expand Up @@ -5,6 +5,7 @@
package binding

import (
"errors"
"io/ioutil"
"net/http"

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

func (protobufBinding) BindBody(body []byte, obj interface{}) error {
if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil {
msg, ok := obj.(proto.Message)
if !ok {
return errors.New("obj is not ProtoMessage")
}
if err := proto.Unmarshal(body, msg); err != nil {
return err
}
// Here it's same to return validate(obj), but util now we can't add
Expand Down

0 comments on commit 15427d3

Please sign in to comment.