This repository has been archived by the owner on Oct 2, 2022. It is now read-only.
generated from ContainerSSH/library-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
marshaller.go
95 lines (80 loc) · 2.15 KB
/
marshaller.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package http
import (
"encoding/json"
"fmt"
"reflect"
)
// responseMarshaller is an interface to cover all encoders for HTTP response bodies.
type responseMarshaller interface {
SupportsMIME(mime string) bool
Marshal(body interface{}) ([]byte, error)
}
//region JSON
type jsonMarshaller struct {
}
func (j *jsonMarshaller) SupportsMIME(mime string) bool {
return mime == "application/json" || mime == "application/*" || mime == "*/*"
}
func (j *jsonMarshaller) Marshal(body interface{}) ([]byte, error) {
return json.Marshal(body)
}
func (j *jsonMarshaller) Unmarshal(body []byte, target interface{}) error {
return json.Unmarshal(body, target)
}
// endregion
// region Text
type TextMarshallable interface {
MarshalText() string
}
type textMarshaller struct {
}
func (t *textMarshaller) SupportsMIME(mime string) bool {
// HTML output might be better suited to piping through a templating engine.
return mime == "text/html" || mime == "text/plain" || mime == "text/*" || mime == "*/*"
}
func (t *textMarshaller) Marshal(body interface{}) ([]byte, error) {
switch assertedBody := body.(type) {
case TextMarshallable:
return []byte(assertedBody.MarshalText()), nil
case string:
return []byte(assertedBody), nil
case int:
return t.marshalNumber(body)
case int8:
return t.marshalNumber(body)
case int16:
return t.marshalNumber(body)
case int32:
return t.marshalNumber(body)
case int64:
return t.marshalNumber(body)
case uint:
return t.marshalNumber(body)
case uint8:
return t.marshalNumber(body)
case uint16:
return t.marshalNumber(body)
case uint32:
return t.marshalNumber(body)
case uint64:
return t.marshalNumber(body)
case bool:
if body.(bool) {
return []byte("true"), nil
} else {
return []byte("false"), nil
}
case uintptr:
return t.marshalPointer(body)
default:
return nil, fmt.Errorf("cannot marshal unknown type: %v", body)
}
}
func (t *textMarshaller) marshalNumber(body interface{}) ([]byte, error) {
return []byte(fmt.Sprintf("%d", body)), nil
}
func (t *textMarshaller) marshalPointer(body interface{}) ([]byte, error) {
ptr := body.(uintptr)
return t.Marshal(reflect.ValueOf(ptr).Elem())
}
// endregion