-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonPResponse.go
70 lines (61 loc) · 1.55 KB
/
jsonPResponse.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
package httpserve
import (
"bytes"
"encoding/json"
"io"
)
var jsonPEnding = []byte(");\n")
// NewJSONPResponse will return a new text response
func NewJSONPResponse(callback string, value interface{}) *JSONPResponse {
var j JSONPResponse
j.callback = callback
j.val = value
return &j
}
// JSONPResponse is a basic text response
type JSONPResponse struct {
callback string
val interface{}
}
// ContentType returns the content type
func (j *JSONPResponse) ContentType() (contentType string) {
return "application/javascript"
}
// StatusCode returns the status code
func (j *JSONPResponse) StatusCode() (code int) {
return 200
}
func (j *JSONPResponse) newValue() (value JSONValue) {
// Switch on associated value's type
switch v := j.val.(type) {
case error:
// Type is a single error value, create new error slice with error as only item
value.Errors.Push(v)
case []error:
// Type is an error slice, set errors as the value
value.Errors.Copy(v)
default:
value.Data = j.val
}
return
}
// WriteTo will write to a given io.Writer
func (j *JSONPResponse) WriteTo(w io.Writer) (n int64, err error) {
// Initialize buffer
buf := bytes.NewBuffer(nil)
// Write callback func
buf.WriteString(j.callback + "(")
// Initialize a new JSON value
value := j.newValue()
// Initialize a new JSON encoder
enc := json.NewEncoder(buf)
// Encode the responder
err = enc.Encode(value)
// Remove the trailing newline
buf.Truncate(buf.Len() - 1)
// Write jsonP ending
buf.Write(jsonPEnding)
// Flush buffer to writer
_, err = w.Write(buf.Bytes())
return
}