-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.go
64 lines (47 loc) · 1.12 KB
/
format.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 api
import (
"encoding/json"
"fmt"
"strings"
"github.com/rs/zerolog/log"
)
// Response define common response methods.
type Response interface {
ToJSON() string
ToTXT() string
ToXML() string
string() string
}
var _ Response = response{}
type response map[string]string
// ToJSON convert the response to JSON.
func (r response) ToJSON() string {
json, err := json.Marshal(r)
if err != nil {
log.Error().Msg("The following JSON encoding failed :")
log.Error().Msg(r.string())
}
return string(json)
}
// ToTXT convert the response to plain text.
func (r response) ToTXT() string {
return r.string()
}
// ToXML convert the response to XML.
func (r response) ToXML() string {
var str strings.Builder
str.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
str.WriteString("<query>")
for key, value := range r {
str.WriteString(fmt.Sprintf("<%v>%v</%v>", key, value, key))
}
str.WriteString("</query>")
return str.String()
}
func (r response) string() string {
var str strings.Builder
for key, value := range r {
str.WriteString(fmt.Sprintf("%v: %v\n", key, value))
}
return str.String()
}