/
jsonp.go
66 lines (55 loc) · 1.53 KB
/
jsonp.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
package jsonp
import (
"encoding/json"
)
const (
// ContentType the custom key for the serializer, when used inside iris, Q web frameworks or simply net/http
ContentType = "application/javascript"
)
// Serializer the serializer which renders a JSONP 'object' with its callback
type Serializer struct {
config Config
}
// New returns a new jsonp serializer
func New(cfg ...Config) *Serializer {
c := DefaultConfig().Merge(cfg)
return &Serializer{config: c}
}
func (e *Serializer) getCallbackOption(options map[string]interface{}) string {
callbackOpt := options["callback"]
if s, isString := callbackOpt.(string); isString {
return s
}
return e.config.Callback
}
var (
finishCallbackB = []byte(");")
newLineB = []byte("\n")
)
// Serialize accepts the 'object' value and converts it to bytes in order to be 'renderable'
// implements the go-serializer.Serializer interface
func (e *Serializer) Serialize(val interface{}, options ...map[string]interface{}) ([]byte, error) {
var result []byte
var err error
if e.config.Indent {
result, err = json.MarshalIndent(val, "", " ")
} else {
result, err = json.Marshal(val)
}
if err != nil {
return nil, err
}
// the config's callback can be overriden with the options
callback := e.config.Callback
if len(options) > 0 {
callback = e.getCallbackOption(options[0])
}
if callback != "" {
result = append([]byte(callback+"("), result...)
result = append(result, finishCallbackB...)
}
if e.config.Indent {
result = append(result, newLineB...)
}
return result, nil
}