95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"runtime"
|
|
|
|
"github.com/graphql-go/graphql"
|
|
)
|
|
|
|
func main() {
|
|
runtime.GOMAXPROCS(runtime.NumCPU())
|
|
|
|
// Schema
|
|
fields := graphql.Fields{
|
|
"hello": &graphql.Field{
|
|
Type: graphql.String,
|
|
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
|
|
return "world", nil
|
|
},
|
|
},
|
|
"users": &graphql.Field{
|
|
Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{
|
|
Name: "User",
|
|
Fields: graphql.Fields{
|
|
"id": &graphql.Field{
|
|
Type: graphql.Int,
|
|
},
|
|
"name": &graphql.Field{
|
|
Type: graphql.String,
|
|
},
|
|
"age": &graphql.Field{
|
|
Type: graphql.Int,
|
|
},
|
|
"info": &graphql.Field{
|
|
Type: graphql.String,
|
|
},
|
|
"price": &graphql.Field{
|
|
Type: graphql.Float,
|
|
},
|
|
},
|
|
})),
|
|
Args: graphql.FieldConfigArgument{
|
|
"id": &graphql.ArgumentConfig{
|
|
Type: graphql.Int,
|
|
},
|
|
},
|
|
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
|
|
fmt.Println("p.Args:", p.Args)
|
|
return []interface{}{
|
|
map[string]interface{}{
|
|
"id": 1,
|
|
"name": "user1",
|
|
"age": 10,
|
|
"info": "info",
|
|
"price": 1.1,
|
|
},
|
|
map[string]interface{}{
|
|
"id": 2,
|
|
"name": "user2",
|
|
"age": 20,
|
|
"info": "info",
|
|
"price": 2.2,
|
|
},
|
|
}, 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.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
|
|
query := r.URL.Query().Get("query")
|
|
fmt.Println("query:", query)
|
|
params := graphql.Params{Schema: schema, RequestString: query}
|
|
result := graphql.Do(params)
|
|
if len(result.Errors) > 0 {
|
|
fmt.Printf("failed to execute graphql operation, errors: %+v", result.Errors)
|
|
http.Error(w, result.Errors[0].Error(), 500)
|
|
return
|
|
}
|
|
rJSON, _ := json.Marshal(result)
|
|
fmt.Printf("%s \n", rJSON) // {"data":{"hello":"world"}}
|
|
w.Write(rJSON)
|
|
})
|
|
|
|
http.ListenAndServe(":8080", nil)
|
|
}
|