/
raw.go
64 lines (51 loc) · 1.68 KB
/
raw.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package encoders
import (
"errors"
"fmt"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"io"
"reflect"
)
// typeOfBytes holds the type of a nil slice of bytes.
var typeOfBytes = reflect.TypeOf([]byte(nil))
var _ runtime.Marshaler = (*rawEncoder)(nil)
// rawEncoder provides methods to copy data into and from slices of bytes.
type rawEncoder struct {
}
// Marshal returns the raw encoding of v. This method expects a slice of bytes.
func (e rawEncoder) Marshal(v interface{}) ([]byte, error) {
b, ok := v.([]byte)
if !ok {
return nil, errors.New("type must be []byte")
}
return b, nil
}
// Unmarshal writes data into v, v must be a pointer to a slice of bytes.
func (e rawEncoder) Unmarshal(data []byte, v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("%T is not a pointer", v)
}
rv = rv.Elem()
if rv.Type() != typeOfBytes {
return fmt.Errorf("type must be []byte but got %T", v)
}
rv.Set(reflect.ValueOf(data))
return nil
}
// NewEncoder returns an Encoder which writes bytes sequence into "w".
func (e rawEncoder) NewEncoder(w io.Writer) runtime.Encoder {
return newEncoderFunc(w, e)
}
// NewDecoder returns a Decoder which reads byte sequence from "r".
func (e rawEncoder) NewDecoder(r io.Reader) runtime.Decoder {
return newDecoderFunc(r, e)
}
// ContentType returns the Content-Type which this marshaler is responsible for.
// The parameter describes the type which is being marshalled, which can sometimes
// affect the content type returned.
func (e rawEncoder) ContentType(v interface{}) string {
return "application/octet-stream"
}
// RAW holds a raw encoder instance implementing Marshaller.
var RAW = &rawEncoder{}