Skip to content

Instantly share code, notes, and snippets.

@harvyso
Created July 26, 2018 20:13
Show Gist options
  • Save harvyso/8526602e319d6879838aa74b509d5c3b to your computer and use it in GitHub Desktop.
Save harvyso/8526602e319d6879838aa74b509d5c3b to your computer and use it in GitHub Desktop.
GraphQL github.com/graphql-go/handler vs REST net/http
package graphql
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
)
func BenchmarkGraphQLHTTP(b *testing.B) {
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
b.Fatalf("failed to create new schema, error: %v", err)
}
h := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: false,
Playground: true,
})
ts := httptest.NewServer(h)
c := http.DefaultClient
for i := 0; i < b.N; i++ {
_, err := c.Post(ts.URL, "application/json", bytes.NewReader([]byte(`{"query":"query { obj { hello }}"}`)))
if err != nil {
b.Fail()
}
}
}
var schemaConfig = graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "RootQuery",
Fields: graphql.Fields{
"obj": &graphql.Field{
Type: graphql.NewObject(graphql.ObjectConfig{
Name: "Obj",
Fields: graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
"prop1": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "proper", nil
},
},
},
}),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
},
}),
}
func BenchmarkHTTP(b *testing.B) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
o := ObjType{Hello: "world", Prop1: "proper"}
json.NewEncoder(w).Encode(o)
})
ts := httptest.NewServer(h)
c := http.DefaultClient
for i := 0; i < b.N; i++ {
_, err := c.Post(ts.URL, "application/json", bytes.NewReader([]byte(`{"query":"query { obj { hello }}"}`)))
if err != nil {
b.Fail()
}
}
}
type ObjType struct {
Hello string `json:"hello"`
Prop1 string `json:"prop1"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment