-
Notifications
You must be signed in to change notification settings - Fork 10
/
proto.go
50 lines (41 loc) · 1.1 KB
/
proto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// +build !appengine
package webrpc
import (
"fmt"
"io"
"io/ioutil"
"code.google.com/p/goprotobuf/proto"
)
// ProtoBuf implements the Google Protocol Buffer implementation of the
// webrpc.Protocol interface. This is currently not allowed on AppEngine.
var ProtoBuf Protocol = pbProtocol{}
type pbProtocol struct{}
func (pbProtocol) String() string { return "application/protobuf" }
func (pbProtocol) Decode(r io.Reader, obj interface{}) error {
pb, ok := obj.(proto.Message)
if !ok {
return fmt.Errorf("%T does not implement proto.Message", obj)
}
body, err := ioutil.ReadAll(r)
if err != nil {
return fmt.Errorf("webrpc: decode: %s", err)
}
return proto.Unmarshal(body, pb)
}
func (pbProtocol) Encode(w io.Writer, obj interface{}) error {
pb, ok := obj.(proto.Message)
if !ok {
return fmt.Errorf("%T does not implement proto.Message", obj)
}
body, err := proto.Marshal(pb)
if err != nil {
return fmt.Errorf("webrpc: encode: %s", err)
}
if _, err := w.Write(body); err != nil {
return fmt.Errorf("webrpc: encode: %s", err)
}
return nil
}
func init() {
RegisterProtocol(ProtoBuf)
}