Skip to content

Commit dd05d5e

Browse files
authored
Merge pull request #575 from graphql-go/examples-http-post
examples: adds http-post example
2 parents 05c348c + 089f1ba commit dd05d5e

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

examples/http-post/main.go

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"net/http"
7+
8+
"github.com/graphql-go/graphql"
9+
"github.com/graphql-go/graphql/examples/todo/schema"
10+
)
11+
12+
type postData struct {
13+
Query string `json:"query"`
14+
Operation string `json:"operation"`
15+
Variables map[string]interface{} `json:"variables"`
16+
}
17+
18+
func main() {
19+
http.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) {
20+
var p postData
21+
if err := json.NewDecoder(req.Body).Decode(&p); err != nil {
22+
w.WriteHeader(400)
23+
return
24+
}
25+
result := graphql.Do(graphql.Params{
26+
Context: req.Context(),
27+
Schema: schema.TodoSchema,
28+
RequestString: p.Query,
29+
VariableValues: p.Variables,
30+
OperationName: p.Operation,
31+
})
32+
if err := json.NewEncoder(w).Encode(result); err != nil {
33+
fmt.Printf("could not write result to response: %s", err)
34+
}
35+
})
36+
37+
fmt.Println("Now server is running on port 8080")
38+
39+
fmt.Println("")
40+
41+
fmt.Println(`Get single todo:
42+
curl \
43+
-X POST \
44+
-H "Content-Type: application/json" \
45+
--data '{ "query": "{ todo(id:\"b\") { id text done } }" }' \
46+
http://localhost:8080/graphql`)
47+
48+
fmt.Println("")
49+
50+
fmt.Println(`Create new todo:
51+
curl \
52+
-X POST \
53+
-H "Content-Type: application/json" \
54+
--data '{ "query": "mutation { createTodo(text:\"My New todo\") { id text done } }" }' \
55+
http://localhost:8080/graphql`)
56+
57+
fmt.Println("")
58+
59+
fmt.Println(`Update todo:
60+
curl \
61+
-X POST \
62+
-H "Content-Type: application/json" \
63+
--data '{ "query": "mutation { updateTodo(id:\"a\", done: true) { id text done } }" }' \
64+
http://localhost:8080/graphql`)
65+
66+
fmt.Println("")
67+
68+
fmt.Println(`Load todo list:
69+
curl \
70+
-X POST \
71+
-H "Content-Type: application/json" \
72+
--data '{ "query": "{ todoList { id text done } }" }' \
73+
http://localhost:8080/graphql`)
74+
75+
http.ListenAndServe(":8080", nil)
76+
}

0 commit comments

Comments
 (0)