Add support for Protobuf format response

This commit is contained in:
salamer 2018-08-12 14:46:43 +08:00
parent 7e64d32269
commit 5682f53f38
3 changed files with 40 additions and 0 deletions

View File

@ -20,6 +20,7 @@ import (
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin/binding"
"github.com/gin-gonic/gin/render"
"github.com/golang/protobuf/proto"
)
// Content-Type MIME of the most common data formats.
@ -835,6 +836,11 @@ func (c *Context) Stream(step func(w io.Writer) bool) {
}
}
// ProtoBuf serializes the given struct as ProtoBuf into the response body.
func (c *Context) ProtoBuf(code int, obj proto.Message) {
c.Render(code, render.ProtoBuf{Data: obj})
}
/************************************/
/******** CONTENT NEGOTIATION *******/
/************************************/

33
render/protobuf.go Normal file
View File

@ -0,0 +1,33 @@
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http"
"github.com/golang/protobuf/proto"
)
type ProtoBuf struct {
Data proto.Message
}
var protobufContentType = []string{"application/x-protobuf"}
func (r ProtoBuf) Render(w http.ResponseWriter) error {
r.WriteContentType(w)
bytes, err := proto.Marshal(r.Data)
if err != nil {
return err
}
w.Write(bytes)
return nil
}
func (r ProtoBuf) WriteContentType(w http.ResponseWriter) {
writeContentType(w, protobufContentType)
}

View File

@ -27,6 +27,7 @@ var (
_ Render = MsgPack{}
_ Render = Reader{}
_ Render = AsciiJSON{}
_ Render = ProtoBuf{}
)
func writeContentType(w http.ResponseWriter, value []string) {