-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
80 lines (68 loc) · 1.45 KB
/
main.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
package main
import (
"io/ioutil"
"log"
"mime/multipart"
"sync"
"github.com/gin-gonic/gin"
"github.com/mjarkk/yarql"
)
func main() {
r := gin.Default()
schema := yarql.NewSchema()
err := schema.Parse(QueryRoot{}, MethodRoot{}, nil)
if err != nil {
log.Fatal(err)
}
// The GraphQL is not thread safe so we use this lock to prevent race conditions and other errors
var lock sync.Mutex
r.Any("/graphql", func(c *gin.Context) {
var form *multipart.Form
getForm := func() (*multipart.Form, error) {
if form != nil {
return form, nil
}
var err error
form, err = c.MultipartForm()
return form, err
}
lock.Lock()
defer lock.Unlock()
res, _ := schema.HandleRequest(
c.Request.Method,
c.Query,
func(key string) (string, error) {
form, err := getForm()
if err != nil {
return "", err
}
values, ok := form.Value[key]
if !ok || len(values) == 0 {
return "", nil
}
return values[0], nil
},
func() []byte {
requestBody, _ := ioutil.ReadAll(c.Request.Body)
return requestBody
},
c.ContentType(),
&yarql.RequestOptions{
GetFormFile: func(key string) (*multipart.FileHeader, error) {
form, err := getForm()
if err != nil {
return nil, err
}
files, ok := form.File[key]
if !ok || len(files) == 0 {
return nil, nil
}
return files[0], nil
},
Tracing: true,
},
)
c.Data(200, "application/json", res)
})
r.Run()
}