Add support for Protobuf format response and unit test (#1479)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
`Gin` now have the `protobufBinding` function to check the request format, but didn't have a protobuf response function like `c.YAML()`. In our company [ByteDance](http://bytedance.com/), the largest internet company using golang in China, we use `gin` to transfer __Protobuf__ instead of __Json__, we have to write some internal library to make some wrappers to achieve that, and the code is not elegant. So we really want such a feature.
authored by aljun · committed by Bo-Yi Wu · parent f856aa8 · Browse files · 6 files·+113 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+113 added−2 removed
- other:+113 added−2 removed
Provenance
- Commit
efdd3c8- Tree
325f622- Author
aljun <salameryy@163.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
f856aa8
6 files changed+113 added−2 removed
added:render/protobuf.go+33 added
1+// Copyright 2018 Gin Core Team. 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 render6+7+import (8+ "net/http"9+10+ "github.com/golang/protobuf/proto"11+)12+13+type ProtoBuf struct {14+ Data proto.Message15+}16+17+var protobufContentType = []string{"application/x-protobuf"}18+19+func (r ProtoBuf) Render(w http.ResponseWriter) error {20+ r.WriteContentType(w)21+22+ bytes, err := proto.Marshal(r.Data)23+ if err != nil {24+ return err25+ }26+27+ w.Write(bytes)28+ return nil29+}30+31+func (r ProtoBuf) WriteContentType(w http.ResponseWriter) {32+ writeContentType(w, protobufContentType)33+}modified:render/render_test.go+31 added
13 unmodified lines14 "strconv"15 "strings"16 "testing"17 18+ testdata "github.com/gin-gonic/gin/testdata/protoexample"19+ "github.com/golang/protobuf/proto"20 "github.com/stretchr/testify/assert"21 "github.com/ugorji/go/codec"22 )23 242 unmodified lines266 err := (YAML{&fail{}}).Render(w)267 assert.Error(t, err)268 }269 270+// test Protobuf rendering271+func TestRenderProtoBuf(t *testing.T) {272+ w := httptest.NewRecorder()273+ reps := []int64{int64(1), int64(2)}274+ label := "test"275+ data := &testdata.Test{276+ Label: &label,277+ Reps: reps,278+ }279+280+ (ProtoBuf{data}).WriteContentType(w)281+ protoData, err := proto.Marshal(data)282+ assert.NoError(t, err)283+ assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))284+285+ err = (ProtoBuf{data}).Render(w)286+287+ assert.NoError(t, err)288+ assert.Equal(t, string(protoData[:]), w.Body.String())289+ assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))290+}291+292+func TestRenderProtoBufFail(t *testing.T) {293+ w := httptest.NewRecorder()294+ data := &testdata.Test{}295+ err := (ProtoBuf{data}).Render(w)296+ assert.Error(t, err)297+}298+299 func TestRenderXML(t *testing.T) {300 w := httptest.NewRecorder()301 data := xmlmap{302 "foo": "bar",182 unmodified linesmodified:render/render.go+1 added
25 unmodified lines26 _ Render = YAML{}27 _ Render = MsgPack{}28 _ Render = Reader{}29 _ Render = AsciiJSON{}30+ _ Render = ProtoBuf{}31 )32 33 func writeContentType(w http.ResponseWriter, value []string) {34 header := w.Header()4 unmodified linesmodified:context_test.go+27 added
18 unmodified lines19 "time"20 21 "github.com/gin-contrib/sse"22 "github.com/gin-gonic/gin/binding"23+ "github.com/golang/protobuf/proto"24 "github.com/stretchr/testify/assert"25 "golang.org/x/net/context"26+27+ testdata "github.com/gin-gonic/gin/testdata/protoexample"28 )29 30 var _ context.Context = &Context{}31 924 unmodified lines956 assert.Equal(t, "foo: bar\n", w.Body.String())957 assert.Equal(t, "application/x-yaml; charset=utf-8", w.HeaderMap.Get("Content-Type"))958 }959 960+// TestContextRenderProtoBuf tests that the response is serialized as ProtoBuf961+// and Content-Type is set to application/x-protobuf962+// and we just use the example protobuf to check if the response is correct963+func TestContextRenderProtoBuf(t *testing.T) {964+ w := httptest.NewRecorder()965+ c, _ := CreateTestContext(w)966+967+ reps := []int64{int64(1), int64(2)}968+ label := "test"969+ data := &testdata.Test{970+ Label: &label,971+ Reps: reps,972+ }973+974+ c.ProtoBuf(http.StatusCreated, data)975+976+ protoData, err := proto.Marshal(data)977+ assert.NoError(t, err)978+979+ assert.Equal(t, http.StatusCreated, w.Code)980+ assert.Equal(t, string(protoData[:]), w.Body.String())981+ assert.Equal(t, "application/x-protobuf", w.HeaderMap.Get("Content-Type"))982+}983+984 func TestContextHeaders(t *testing.T) {985 c, _ := CreateTestContext(httptest.NewRecorder())986 c.Header("Content-Type", "text/plain")987 c.Header("X-Custom", "value")700 unmodified linesmodified:context.go+6 added
18 unmodified lines19 20 "github.com/gin-contrib/sse"21 "github.com/gin-gonic/gin/binding"22 "github.com/gin-gonic/gin/render"23+ "github.com/golang/protobuf/proto"24 )25 26 // Content-Type MIME of the most common data formats.27 const (817 unmodified lines845 }846 }847 }848 849+// ProtoBuf serializes the given struct as ProtoBuf into the response body.850+func (c *Context) ProtoBuf(code int, obj proto.Message) {851+ c.Render(code, render.ProtoBuf{Data: obj})852+}853+854 /************************************/855 /******** CONTENT NEGOTIATION *******/856 /************************************/857 92 unmodified linesmodified:README.md+15 added-2 removed
38 unmodified lines39 - [Only Bind Query String](#only-bind-query-string)40 - [Bind Query String or Post Data](#bind-query-string-or-post-data)41 - [Bind HTML checkboxes](#bind-html-checkboxes)42 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)43- - [XML, JSON and YAML rendering](#xml-json-and-yaml-rendering)43+ - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering)44 - [JSONP rendering](#jsonp)45 - [Serving static files](#serving-static-files)46 - [Serving data from reader](#serving-data-from-reader)47 - [HTML rendering](#html-rendering)822 unmodified lines870 ```sh871 $ curl -v --form user=user --form password=password http://localhost:8080/login872 ```873 874-### XML, JSON and YAML rendering874+### XML, JSON, YAML and ProtoBuf rendering875 876 ```go877 func main() {878 r := gin.Default()25 unmodified lines904 r.GET("/someYAML", func(c *gin.Context) {905 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})906 })907 908+ r.GET("/someProtoBuf", func(c *gin.Context) {909+ reps := []int64{int64(1), int64(2)}910+ label := "test"911+ // The specific definition of protobuf is written in the testdata/protoexample file.912+ data := &protoexample.Test{913+ Label: &label,914+ Reps: reps,915+ }916+ // Note that data becomes binary data in the response917+ // Will output protoexample.Test protobuf serialized data918+ c.ProtoBuf(http.StatusOK, data)919+ })920+921 // Listen and serve on 0.0.0.0:8080922 r.Run(":8080")923 }924 ```934 unmodified lines