Skip to content

Commit

Permalink
added relay.Handler
Browse files Browse the repository at this point in the history
  • Loading branch information
neelance committed Nov 7, 2016
1 parent fce75a5 commit 8f7d2b1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
23 changes: 2 additions & 21 deletions example/starwars/server/server.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package main

import (
"encoding/json"
"log"
"net/http"

"github.com/neelance/graphql-go"
"github.com/neelance/graphql-go/example/starwars"
"github.com/neelance/graphql-go/relay"
)

var schema *graphql.Schema
Expand All @@ -24,26 +24,7 @@ func main() {
w.Write(page)
}))

http.HandleFunc("/query", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

response := schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Write(responseJSON)
}))
http.Handle("/query", &relay.Handler{Schema: schema})

log.Fatal(http.ListenAndServe(":8080", nil))
}
Expand Down
26 changes: 26 additions & 0 deletions relay/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"strings"

"encoding/json"
Expand Down Expand Up @@ -42,3 +43,28 @@ func UnmarshalSpec(id graphql.ID, v interface{}) error {
}
return json.Unmarshal([]byte(s[i+1:]), v)
}

type Handler struct {
Schema *graphql.Schema
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Write(responseJSON)
}

0 comments on commit 8f7d2b1

Please sign in to comment.