-
-
Notifications
You must be signed in to change notification settings - Fork 455
/
main.go
75 lines (63 loc) · 1.96 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
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/graphql-go/graphql"
)
type Input struct {
Query string `query:"query"`
OperationName string `query:"operationName"`
Variables map[string]interface{} `query:"variables"`
}
func main() {
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
}
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
log.Fatalf("failed to create new schema, error: %v", err)
}
app := fiber.New()
// curl 'http://localhost:9090/?query=query%7Bhello%7D'
app.Get("/", func(ctx *fiber.Ctx) error {
var input Input
if err := ctx.QueryParser(&input); err != nil {
return ctx.
Status(fiber.StatusInternalServerError).
SendString("Cannot parse query parameters: " + err.Error())
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: input.Query,
OperationName: input.OperationName,
VariableValues: input.Variables,
})
ctx.Set("Content-Type", "application/graphql-response+json")
return ctx.JSON(result)
})
// curl 'http://localhost:9090/' --header 'content-type: application/json' --data-raw '{"query":"query{hello}"}'
app.Post("/", func(ctx *fiber.Ctx) error {
var input Input
if err := ctx.BodyParser(&input); err != nil {
return ctx.
Status(fiber.StatusInternalServerError).
SendString("Cannot parse body: " + err.Error())
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: input.Query,
OperationName: input.OperationName,
VariableValues: input.Variables,
})
ctx.Set("Content-Type", "application/graphql-response+json")
return ctx.JSON(result)
})
log.Fatal(app.Listen(":9090"))
}