Skip to content
Myr

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

6 files+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.45package render67import (8 "net/http"910 "github.com/golang/protobuf/proto"11)1213type ProtoBuf struct {14 Data proto.Message15}1617var protobufContentType = []string{"application/x-protobuf"}1819func (r ProtoBuf) Render(w http.ResponseWriter) error {20 r.WriteContentType(w)2122 bytes, err := proto.Marshal(r.Data)23 if err != nil {24 return err25 }2627 w.Write(bytes)28 return nil29}3031func (r ProtoBuf) WriteContentType(w http.ResponseWriter) {32 writeContentType(w, protobufContentType)33}
modified:render/render_test.go+31 added
13 unmodified lines
14 "strconv"15 "strings"16 "testing"1718 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 lines
266 err := (YAML{&fail{}}).Render(w)267 assert.Error(t, err)268}269270// test Protobuf rendering271func 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 }279280 (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"))284285 err = (ProtoBuf{data}).Render(w)286287 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}291292func TestRenderProtoBufFail(t *testing.T) {293 w := httptest.NewRecorder()294 data := &testdata.Test{}295 err := (ProtoBuf{data}).Render(w)296 assert.Error(t, err)297}298299func TestRenderXML(t *testing.T) {300 w := httptest.NewRecorder()301 data := xmlmap{302 "foo": "bar",
182 unmodified lines
modified:render/render.go+1 added
25 unmodified lines
26 _ Render = YAML{}27 _ Render = MsgPack{}28 _ Render = Reader{}29 _ Render = AsciiJSON{}30 _ Render = ProtoBuf{}31)3233func writeContentType(w http.ResponseWriter, value []string) {34 header := w.Header()
4 unmodified lines
modified:context_test.go+27 added
18 unmodified lines
19 "time"2021 "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"2627 testdata "github.com/gin-gonic/gin/testdata/protoexample"28)2930var _ context.Context = &Context{}31
924 unmodified lines
956 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}959960// 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 correct963func TestContextRenderProtoBuf(t *testing.T) {964 w := httptest.NewRecorder()965 c, _ := CreateTestContext(w)966967 reps := []int64{int64(1), int64(2)}968 label := "test"969 data := &testdata.Test{970 Label: &label,971 Reps: reps,972 }973974 c.ProtoBuf(http.StatusCreated, data)975976 protoData, err := proto.Marshal(data)977 assert.NoError(t, err)978979 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}983984func TestContextHeaders(t *testing.T) {985 c, _ := CreateTestContext(httptest.NewRecorder())986 c.Header("Content-Type", "text/plain")987 c.Header("X-Custom", "value")
700 unmodified lines
modified:context.go+6 added
18 unmodified lines
1920 "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)2526// Content-Type MIME of the most common data formats.27const (
817 unmodified lines
845 }846 }847}848849// ProtoBuf serializes the given struct as ProtoBuf into the response body.850func (c *Context) ProtoBuf(code int, obj proto.Message) {851 c.Render(code, render.ProtoBuf{Data: obj})852}853854/************************************/855/******** CONTENT NEGOTIATION *******/856/************************************/857
92 unmodified lines
modified:README.md+15 added-2 removed
38 unmodified lines
39 - [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 lines
870```sh871$ curl -v --form user=user --form password=password http://localhost:8080/login872```873874### XML, JSON and YAML rendering874### XML, JSON, YAML and ProtoBuf rendering875876```go877func main() {878 r := gin.Default()
25 unmodified lines
904 r.GET("/someYAML", func(c *gin.Context) {905 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})906 })907908 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 })920921 // Listen and serve on 0.0.0.0:8080922 r.Run(":8080")923}924```
934 unmodified lines