forked from jim3ma/gin-jsonp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsonp.go
171 lines (145 loc) · 3.4 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package jsonp
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
const (
noWritten = -1
defaultStatus = 200
)
// Handler wraps responses in JSONP function
func Handler() gin.HandlerFunc {
return func(c *gin.Context) {
callback := c.DefaultQuery("callback", "")
if callback == "" {
callback = c.DefaultQuery("jsonp", "")
if callback == "" {
c.Next()
return
}
}
var wb *responseBuffer
if w, ok := c.Writer.(gin.ResponseWriter); ok {
wb = newResponseBuffer(w)
c.Writer = wb
c.Next()
} else {
c.Next()
return
}
if strings.Index(wb.Header().Get("Content-Type"), "/json") >= 0 {
status := wb.status
data := wb.Body.Bytes()
wb.Body.Reset()
resp := &jsonpResponse{
Meta: map[string]interface{}{"status": status},
Data: data,
}
for k, v := range wb.Header() {
resp.Meta[strings.ToLower(k)] = v[0]
}
resp.Meta["content-length"] = len(data)
body, err := json.Marshal(resp)
if err != nil {
panic(err.Error())
}
wb.Body.Write([]byte(callback + "("))
wb.Body.Write(body)
wb.Body.Write([]byte(")"))
wb.Header().Set("Content-Type", "application/javascript")
wb.Header().Set("Content-Length", strconv.Itoa(wb.Body.Len()))
}
wb.Flush()
}
}
type jsonpResponse struct {
Meta map[string]interface{}
Data interface{}
}
// MarshalJSON marshals the entire response, with headers
func (j *jsonpResponse) MarshalJSON() ([]byte, error) {
meta, err := json.Marshal(j.Meta)
if err != nil {
return nil, err
}
b := fmt.Sprintf("{\"meta\":%s,\"data\":%s}", meta, j.Data)
return []byte(b), nil
}
type responseBuffer struct {
Response gin.ResponseWriter // the actual ResponseWriter to flush to
status int // the HTTP response code from WriteHeader
Body *bytes.Buffer // the response content body
Flushed bool
}
func newResponseBuffer(w gin.ResponseWriter) *responseBuffer {
return &responseBuffer{
Response: w, status: defaultStatus, Body: &bytes.Buffer{},
}
}
func (w *responseBuffer) Header() http.Header {
return w.Response.Header() // use the actual response header
}
func (w *responseBuffer) Write(buf []byte) (int, error) {
w.Body.Write(buf)
return len(buf), nil
}
func (w *responseBuffer) WriteString(s string) (n int, err error) {
//w.WriteHeaderNow()
//n, err = io.WriteString(w.ResponseWriter, s)
//w.size += n
n, err = w.Write([]byte(s))
return
}
func (w *responseBuffer) Written() bool {
return w.Body.Len() != noWritten
}
func (w *responseBuffer) WriteHeader(status int) {
w.status = status
}
func (w *responseBuffer) WriteHeaderNow() {
//if !w.Written() {
// w.size = 0
// w.ResponseWriter.WriteHeader(w.status)
//}
}
func (w *responseBuffer) Status() int {
return w.status
}
func (w *responseBuffer) Size() int {
return w.Body.Len()
}
func (w *responseBuffer) Hijack() (net.Conn, *bufio.ReadWriter, error) {
//if w.size < 0 {
// w.size = 0
//}
return w.Response.(http.Hijacker).Hijack()
}
func (w *responseBuffer) CloseNotify() <-chan bool {
return w.Response.(http.CloseNotifier).CloseNotify()
}
// Fake Flush
// TBD
func (w *responseBuffer) Flush() {
w.realFlush()
}
func (w *responseBuffer) realFlush() {
if w.Flushed {
return
}
w.Response.WriteHeader(w.status)
if w.Body.Len() > 0 {
_, err := w.Response.Write(w.Body.Bytes())
if err != nil {
panic(err)
}
w.Body.Reset()
}
w.Flushed = true
}