-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhandler.go
206 lines (187 loc) · 4.98 KB
/
handler.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package handler
import (
"context"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"regexp"
"strconv"
"strings"
)
type Handler struct {
MaxBodySize int64 // in bytes
Executor Executor
Client bool
}
type Request struct {
OperationName string `json:"operationName"`
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
Context context.Context
}
func set(v interface{}, m interface{}, path string) error {
var parts []interface{}
for _, p := range strings.Split(path, ".") {
if isNumber, err := regexp.MatchString(`\d+`, p); err != nil {
return err
} else if isNumber {
index, _ := strconv.Atoi(p)
parts = append(parts, index)
} else {
parts = append(parts, p)
}
}
for i, p := range parts {
last := i == len(parts)-1
switch idx := p.(type) {
case string:
if last {
m.(map[string]interface{})[idx] = v
} else {
m = m.(map[string]interface{})[idx]
}
case int:
if last {
m.([]interface{})[idx] = v
} else {
m = m.([]interface{})[idx]
}
}
}
return nil
}
type File struct {
File multipart.File
Filename string
Size int64
}
type Config struct {
MaxBodySize int64
}
type Executor func(request *Request) interface{}
type Factory func(http.ResponseWriter, *http.Request) interface{}
func New(executor Executor, config *Config) *Handler {
return &Handler{
MaxBodySize: config.MaxBodySize,
Executor: executor,
}
}
func (self *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var operations interface{}
if r.Method == "GET" {
request := Request{Context: r.Context()}
// Get query
if value := r.URL.Query().Get("query"); len(value) == 0 {
message := fmt.Sprintf("Missing query")
http.Error(w, message, http.StatusBadRequest)
return
} else {
request.Query = value
}
// Get variables
if value := r.URL.Query().Get("variables"); len(value) == 0 {
request.Variables = map[string]interface{}{}
} else if err := json.Unmarshal([]byte(value), &request.Variables); err != nil {
message := fmt.Sprintf("Bad variables")
http.Error(w, message, http.StatusBadRequest)
return
}
// Get variables
if value := r.URL.Query().Get("operationName"); len(value) == 0 {
request.OperationName = ""
} else {
request.OperationName = value
}
result := self.Executor(&request)
if err := json.NewEncoder(w).Encode(result); err != nil {
panic(err)
}
} else if r.Method == "POST" {
contentType := strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0]
switch contentType {
case "text/plain", "application/json":
if err := json.NewDecoder(r.Body).Decode(&operations); err != nil {
panic(err)
}
case "multipart/form-data":
// Parse multipart form
if err := r.ParseMultipartForm(self.MaxBodySize); err != nil {
panic(err)
}
// Unmarshal uploads
var uploads = map[File][]string{}
var uploadsMap = map[string][]string{}
if err := json.Unmarshal([]byte(r.Form.Get("map")), &uploadsMap); err != nil {
panic(err)
} else {
for key, path := range uploadsMap {
if file, header, err := r.FormFile(key); err != nil {
panic(err)
//w.WriteHeader(http.StatusInternalServerError)
//return
} else {
uploads[File{
File: file,
Size: header.Size,
Filename: header.Filename,
}] = path
}
}
}
// Unmarshal operations
if err := json.Unmarshal([]byte(r.Form.Get("operations")), &operations); err != nil {
panic(err)
}
// set uploads to operations
for file, paths := range uploads {
for _, path := range paths {
if err := set(file, operations, path); err != nil {
panic(err)
}
}
}
}
switch data := operations.(type) {
case map[string]interface{}:
request := Request{}
if value, ok := data["operationName"]; ok && value != nil {
request.OperationName = value.(string)
}
if value, ok := data["query"]; ok && value != nil {
request.Query = value.(string)
}
if value, ok := data["variables"]; ok && value != nil {
request.Variables = value.(map[string]interface{})
}
request.Context = r.Context()
if err := json.NewEncoder(w).Encode(self.Executor(&request)); err != nil {
panic(err)
}
case []interface{}:
result := make([]interface{}, len(data))
for index, operation := range data {
data := operation.(map[string]interface{})
request := Request{}
if value, ok := data["operationName"]; ok {
request.OperationName = value.(string)
}
if value, ok := data["query"]; ok {
request.Query = value.(string)
}
if value, ok := data["variables"]; ok {
request.Variables = value.(map[string]interface{})
}
request.Context = r.Context()
result[index] = self.Executor(&request)
}
if err := json.NewEncoder(w).Encode(result); err != nil {
panic(err)
}
default:
w.WriteHeader(http.StatusBadRequest)
return
}
}
}