add protobuf binding for gin
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by zhing · committed by zhing · parent 0d1b985 · Browse files · 5 files·+201 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+201 added−3 removed
- other:+201 added−3 removed
Provenance
- Commit
9d644d2- Tree
d257bcd- Author
zhing <zqwillseven@gmail.com>- Committer
zhing <zqwillseven@gmail.com>- Parent
0d1b985
5 files changed+201 added−3 removed
added:binding/example/test.pb.go+113 added
1+// Code generated by protoc-gen-go.2+// source: test.proto3+// DO NOT EDIT!4+5+/*6+Package example is a generated protocol buffer package.7+8+It is generated from these files:9+ test.proto10+11+It has these top-level messages:12+ Test13+*/14+package example15+16+import proto "github.com/golang/protobuf/proto"17+import math "math"18+19+// Reference imports to suppress errors if they are not otherwise used.20+var _ = proto.Marshal21+var _ = math.Inf22+23+type FOO int3224+25+const (26+ FOO_X FOO = 1727+)28+29+var FOO_name = map[int32]string{30+ 17: "X",31+}32+var FOO_value = map[string]int32{33+ "X": 17,34+}35+36+func (x FOO) Enum() *FOO {37+ p := new(FOO)38+ *p = x39+ return p40+}41+func (x FOO) String() string {42+ return proto.EnumName(FOO_name, int32(x))43+}44+func (x *FOO) UnmarshalJSON(data []byte) error {45+ value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO")46+ if err != nil {47+ return err48+ }49+ *x = FOO(value)50+ return nil51+}52+53+type Test struct {54+ Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`55+ Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`56+ Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`57+ Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`58+ XXX_unrecognized []byte `json:"-"`59+}60+61+func (m *Test) Reset() { *m = Test{} }62+func (m *Test) String() string { return proto.CompactTextString(m) }63+func (*Test) ProtoMessage() {}64+65+const Default_Test_Type int32 = 7766+67+func (m *Test) GetLabel() string {68+ if m != nil && m.Label != nil {69+ return *m.Label70+ }71+ return ""72+}73+74+func (m *Test) GetType() int32 {75+ if m != nil && m.Type != nil {76+ return *m.Type77+ }78+ return Default_Test_Type79+}80+81+func (m *Test) GetReps() []int64 {82+ if m != nil {83+ return m.Reps84+ }85+ return nil86+}87+88+func (m *Test) GetOptionalgroup() *Test_OptionalGroup {89+ if m != nil {90+ return m.Optionalgroup91+ }92+ return nil93+}94+95+type Test_OptionalGroup struct {96+ RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`97+ XXX_unrecognized []byte `json:"-"`98+}99+100+func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }101+func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }102+func (*Test_OptionalGroup) ProtoMessage() {}103+104+func (m *Test_OptionalGroup) GetRequiredField() string {105+ if m != nil && m.RequiredField != nil {106+ return *m.RequiredField107+ }108+ return ""109+}110+111+func init() {112+ proto.RegisterEnum("example.FOO", FOO_name, FOO_value)113+}added:binding/example/test.proto+12 added
1+package example;2+3+enum FOO {X=17;};4+5+message Test {6+ required string label = 1;7+ optional int32 type = 2[default=77];8+ repeated int64 reps = 3;9+ optional group OptionalGroup = 4{10+ required string RequiredField = 5;11+ }12+}modified:binding/binding_test.go+34 added
4 unmodified lines5 package binding6 7 import (8 "bytes"9+ "github.com/gin-gonic/gin/binding/example"10+ "github.com/golang/protobuf/proto"11 "net/http"12 "testing"13 14 "github.com/stretchr/testify/assert"22 unmodified lines37 assert.Equal(t, Default("PUT", MIMEPOSTForm), Form)38 39 assert.Equal(t, Default("POST", MIMEMultipartPOSTForm), Form)40 assert.Equal(t, Default("PUT", MIMEMultipartPOSTForm), Form)41+42+ assert.Equal(t, Default("POST", MIMEPROTOBUF), ProtoBuf)43+ assert.Equal(t, Default("PUT", MIMEPROTOBUF), ProtoBuf)44 }45 46 func TestBindingJSON(t *testing.T) {47 testBodyBinding(t,20 unmodified lines68 "/", "/",69 "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")70 }71 72+func TestBindingProtoBuf(t *testing.T) {73+ test := &example.Test{74+ Label: proto.String("yes"),75+ }76+ data, _ := proto.Marshal(test)77+78+ testProtoBodyBinding(t,79+ ProtoBuf, "protobuf",80+ "/", "/",81+ string(data), string(data[1:]))82+}83+84 func TestValidationFails(t *testing.T) {85 var obj FooStruct86 req := requestWithBody("POST", "/", `{"bar": "foo"}`)87 err := JSON.Bind(req, &obj)45 unmodified lines133 err = JSON.Bind(req, &obj)134 assert.Error(t, err)135 }136 137+func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {138+ assert.Equal(t, b.Name(), name)139+140+ obj := example.Test{}141+ req := requestWithBody("POST", path, body)142+ req.Header.Add("Content-Type", MIMEPROTOBUF)143+ err := b.Bind(req, &obj)144+ assert.NoError(t, err)145+ assert.Equal(t, *obj.Label, "yes")146+147+ obj = example.Test{}148+ req = requestWithBody("POST", badPath, badBody)149+ req.Header.Add("Content-Type", MIMEPROTOBUF)150+ err = ProtoBuf.Bind(req, &obj)151+ assert.Error(t, err)152+}153+154 func requestWithBody(method, path, body string) (req *http.Request) {155 req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))156 return157 }modified:binding/binding.go+7 added-3 removed
12 unmodified lines13 MIMEXML2 = "text/xml"14 MIMEPlain = "text/plain"15 MIMEPOSTForm = "application/x-www-form-urlencoded"16 MIMEMultipartPOSTForm = "multipart/form-data"17+ MIMEPROTOBUF = "application/octet-stream"18 )19 20 type Binding interface {21 Name() string11 unmodified lines33 34 var Validator StructValidator = &defaultValidator{}35 36 var (36- JSON = jsonBinding{}37- XML = xmlBinding{}38- Form = formBinding{}37+ JSON = jsonBinding{}38+ XML = xmlBinding{}39+ Form = formBinding{}40+ ProtoBuf = protobufBinding{}41 )42 43 func Default(method, contentType string) Binding {44 if method == "GET" {3 unmodified lines48 case MIMEJSON:49 return JSON50 case MIMEXML, MIMEXML2:51 return XML52+ case MIMEPROTOBUF:53+ return ProtoBuf54 default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:55 return Form56 }57 }8 unmodified linesadded:binding/protobuf.go+35 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "github.com/golang/protobuf/proto"9+10+ "io/ioutil"11+ "net/http"12+)13+14+type protobufBinding struct{}15+16+func (_ protobufBinding) Name() string {17+ return "protobuf"18+}19+20+func (_ protobufBinding) Bind(req *http.Request, obj interface{}) error {21+22+ buf, err := ioutil.ReadAll(req.Body)23+ if err != nil {24+ return err25+ }26+27+ if err = proto.Unmarshal(buf, obj.(proto.Message)); err != nil {28+ return err29+ }30+31+ //Here it's same to return validate(obj), but util now we cann't add `binding:""` to the struct32+ //which automatically generate by gen-proto33+ return nil34+ //return validate(obj)35+}