-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_entity.go
71 lines (55 loc) · 1.13 KB
/
response_entity.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
package stgin
import (
"encoding/json"
"encoding/xml"
)
const (
applicationJson = "application/json"
applicationXml = "application/xml"
plainText = "text/plain"
)
type ResponseEntity interface {
ContentType() string
Bytes() ([]byte, error)
}
func marshall(re ResponseEntity) (bytes []byte, contentType string, err error) {
bytes, err = re.Bytes()
contentType = re.ContentType()
return
}
type jsonEntity struct {
obj any
}
func (j jsonEntity) ContentType() string {
return applicationJson
}
func (j jsonEntity) Bytes() ([]byte, error) {
return json.Marshal(j.obj)
}
type xmlEntity struct {
obj any
}
func (xe xmlEntity) ContentType() string {
return applicationXml
}
func (xe xmlEntity) Bytes() ([]byte, error) {
return xml.Marshal(xe.obj)
}
type textEntity struct {
obj string
}
func (t textEntity) ContentType() string {
return plainText
}
func (t textEntity) Bytes() ([]byte, error) {
return []byte(t.obj), nil
}
func Json(a any) ResponseEntity {
return jsonEntity{obj: a}
}
func Xml(a any) ResponseEntity {
return xmlEntity{obj: a}
}
func Text(text string) ResponseEntity {
return textEntity{obj: text}
}