Skip to content

Instantly share code, notes, and snippets.

@birowo
Last active October 23, 2018 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save birowo/371d2d895b2b9ddada91c65e41d4fee6 to your computer and use it in GitHub Desktop.
Save birowo/371d2d895b2b9ddada91c65e41d4fee6 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/graphql-go/graphql"
)
func main() {
// Schema
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"param1": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Args["param1"], 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)
}
http.ListenAndServe(":8080", http.HandlerFunc(func(hrw http.ResponseWriter, hr *http.Request) {
// Query
query := hr.URL.Query()
if len(query) == 0 {
hrw.Header().Set("Content-Type", "text/html; charset=utf-8")
hrw.Write([]byte(`<a href='/?query={ hello(param1: "world") }'>hello</a>`))
return
}
for k, v := range query {
switch k {
case "query":
params := graphql.Params{Schema: schema, RequestString: v[0]}
r := graphql.Do(params)
if len(r.Errors) > 0 {
log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
}
hrw.Header().Set("Content-Type", "application/json")
json.NewEncoder(hrw).Encode(r)
default:
hrw.WriteHeader(http.StatusNotFound)
hrw.Write([]byte("resource not found"))
}
return
}
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment