-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathtodo.go
More file actions
107 lines (87 loc) · 1.9 KB
/
todo.go
File metadata and controls
107 lines (87 loc) · 1.9 KB
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
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
)
var Schema = `
schema {
query: Query
}
type Query {
viewerTodos: [Todo!]!
}
type Todo {
title: String!
done: Boolean!
}
`
type Todo struct {
title string
done bool
}
func (t *Todo) Title() string {
return t.title
}
func (t *Todo) Done() bool {
return t.done
}
// the list of todos for each user
var todos = map[string][]*Todo{
"1": {
{
title: "Foo 1",
},
{
title: "Bar 1",
},
},
"2": {
{
title: "Foo 2",
},
{
title: "Bar 2",
},
{
title: "Baz 2",
},
},
"3": {},
}
type query struct{}
// look up the list of todos for the current user
func (r *query) ViewerTodos(ctx context.Context) ([]*Todo, error) {
// grab the current user from the context
userID, ok := ctx.Value("user-id").(string)
if !ok {
return nil, errors.New("user ID was not a string")
}
fmt.Println("Hello", userID)
// return the todos for the appropriate user
return todos[userID], nil
}
// addUserInfo is a handler middleware that extracts the appropriate header and sets it
// to a known place in context
func addUserInfo(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// before we invoke the graphql endpoint we need to add the current
// user to the context
// look up the value of the USER_ID header
userID := r.Header.Get("USER_ID")
// set the value in context
ctx := context.WithValue(r.Context(), "user-id", userID)
// pass the handler args to the wrapped handler
handler.ServeHTTP(w, r.WithContext(ctx))
})
}
func main() {
schema := graphql.MustParseSchema(Schema, &query{})
// make sure we add the user info to the execution context
http.Handle("/", addUserInfo(&relay.Handler{Schema: schema}))
log.Fatal(http.ListenAndServe(":8081", nil))
}