Skip to content

Commit cb98aa4

Browse files
maaptehchris-ramon
authored andcommitted
examples: adds http-post example
1 parent 05c348c commit cb98aa4

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

examples/http-post/main.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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\n")
38+
39+
fmt.Println(`Get single todo:
40+
curl \
41+
-X POST \
42+
-H "Content-Type: application/json" \
43+
--data '{ "query": "{ todo(id:\"b\") { id text done } }" }' \
44+
http://localhost:8080/graphql
45+
`)
46+
47+
fmt.Println(`Create new todo:
48+
curl \
49+
-X POST \
50+
-H "Content-Type: application/json" \
51+
--data '{ "query": "mutation { createTodo(text:\"My New todo\") { id text done } }" }' \
52+
http://localhost:8080/graphql
53+
`)
54+
55+
fmt.Println(`Update todo:
56+
curl \
57+
-X POST \
58+
-H "Content-Type: application/json" \
59+
--data '{ "query": "mutation { updateTodo(id:\"a\", done: true) { id text done } }" }' \
60+
http://localhost:8080/graphql
61+
`)
62+
63+
fmt.Println(`Load todo list:
64+
curl \
65+
-X POST \
66+
-H "Content-Type: application/json" \
67+
--data '{ "query": "{ todoList { id text done } }" }' \
68+
http://localhost:8080/graphql`)
69+
70+
http.ListenAndServe(":8080", nil)
71+
}

0 commit comments

Comments
 (0)