Convert Figma logo to code with AI

graphql-go logographql

An implementation of GraphQL for Go / Golang

9,900
841
9,900
226

Top Related Projects

9,867

go generate based graphql server library

1,584

⚡️ A Go framework for rapidly building powerful graphql services

GraphQL server with a focus on ease of use

Quick Overview

graphql-go/graphql is a Go implementation of GraphQL, providing a powerful and flexible way to build GraphQL servers in Go. It offers a complete set of tools to define schemas, resolve queries, and handle mutations, making it easier for developers to create GraphQL APIs in Go applications.

Pros

  • Comprehensive implementation of the GraphQL specification
  • Flexible and extensible architecture
  • Good performance and scalability
  • Active community and ongoing development

Cons

  • Steeper learning curve compared to some other GraphQL libraries
  • Documentation could be more extensive and up-to-date
  • Some advanced features may require additional setup or custom implementations

Code Examples

  1. Defining a simple schema:
import "github.com/graphql-go/graphql"

var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query: graphql.NewObject(graphql.ObjectConfig{
        Name: "RootQuery",
        Fields: graphql.Fields{
            "hello": &graphql.Field{
                Type: graphql.String,
                Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                    return "world", nil
                },
            },
        },
    }),
})
  1. Executing a query:
query := `
    {
        hello
    }
`
result := graphql.Do(graphql.Params{
    Schema:        schema,
    RequestString: query,
})
fmt.Println(result)
  1. Defining a mutation:
var mutationType = graphql.NewObject(graphql.ObjectConfig{
    Name: "Mutation",
    Fields: graphql.Fields{
        "createUser": &graphql.Field{
            Type: userType,
            Args: graphql.FieldConfigArgument{
                "name": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.String)},
            },
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                name := p.Args["name"].(string)
                // Create user logic here
                return User{ID: "1", Name: name}, nil
            },
        },
    },
})

Getting Started

To start using graphql-go/graphql in your Go project:

  1. Install the package:

    go get github.com/graphql-go/graphql
    
  2. Import the package in your Go file:

    import "github.com/graphql-go/graphql"
    
  3. Define your schema and create a GraphQL handler:

    schema, _ := graphql.NewSchema(graphql.SchemaConfig{
        Query: rootQuery,
        Mutation: mutationType,
    })
    
    h := handler.New(&handler.Config{
        Schema: &schema,
        Pretty: true,
    })
    http.Handle("/graphql", h)
    
  4. Start your HTTP server and begin handling GraphQL requests.

Competitor Comparisons

9,867

go generate based graphql server library

Pros of gqlgen

  • Code generation approach leads to type-safe, efficient code
  • Supports GraphQL schema-first development
  • Integrates well with existing Go code and types

Cons of gqlgen

  • Steeper learning curve due to code generation concepts
  • Requires additional setup and configuration

Code Comparison

gqlgen:

type Query struct {
    Todo TodoResolver
}

func (q *Query) Todo(ctx context.Context, id string) (*Todo, error) {
    // Implementation
}

graphql:

var queryType = graphql.NewObject(graphql.ObjectConfig{
    Name: "Query",
    Fields: graphql.Fields{
        "todo": &graphql.Field{
            Type: todoType,
            Args: graphql.FieldConfigArgument{
                "id": &graphql.ArgumentConfig{Type: graphql.String},
            },
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                // Implementation
            },
        },
    },
})

Key Differences

  • gqlgen generates Go code from GraphQL schema, while graphql requires manual definition of types and resolvers
  • gqlgen provides stronger type safety and better integration with Go's type system
  • graphql offers more flexibility in defining schema and resolvers programmatically
  • gqlgen has a more opinionated structure, while graphql allows for more customization in implementation

Both libraries are popular choices for implementing GraphQL in Go, with gqlgen being more suited for larger, schema-first projects, and graphql offering more flexibility for smaller or more dynamic implementations.

1,584

⚡️ A Go framework for rapidly building powerful graphql services

Pros of Thunder

  • Built-in support for real-time subscriptions and live queries
  • Automatic batching and caching of database queries for improved performance
  • Simplified schema definition using Go structs and tags

Cons of Thunder

  • Less mature and less widely adopted compared to graphql
  • Limited documentation and community resources
  • May have a steeper learning curve for developers new to GraphQL

Code Comparison

Thunder schema definition:

type User struct {
    ID   graphql.ID `graphql:"id"`
    Name string     `graphql:"name"`
}

schema.Object("User", User{})

graphql schema definition:

var userType = graphql.NewObject(graphql.ObjectConfig{
    Name: "User",
    Fields: graphql.Fields{
        "id":   &graphql.Field{Type: graphql.ID},
        "name": &graphql.Field{Type: graphql.String},
    },
})

Thunder offers a more concise and Go-idiomatic approach to schema definition, using struct tags. graphql requires more verbose configuration using GraphQL-specific types and fields.

Both libraries provide robust GraphQL implementations for Go, but Thunder focuses on performance optimizations and real-time capabilities, while graphql offers a more traditional and widely adopted approach. The choice between them depends on specific project requirements and developer preferences.

GraphQL server with a focus on ease of use

Pros of graphql-go

  • More type-safe implementation
  • Better performance, especially for complex queries
  • Supports custom scalar types out of the box

Cons of graphql-go

  • Steeper learning curve
  • Less flexible schema definition
  • Fewer examples and community resources

Code Comparison

graphql:

var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query: graphql.NewObject(graphql.ObjectConfig{
        Name: "Query",
        Fields: graphql.Fields{
            "hello": &graphql.Field{
                Type: graphql.String,
                Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                    return "world", nil
                },
            },
        },
    }),
})

graphql-go:

var Schema = `
    type Query {
        hello: String!
    }
`

type query struct{}

func (q *query) Hello() string {
    return "world"
}

Both libraries offer robust GraphQL implementations for Go, but they differ in their approach. graphql focuses on simplicity and ease of use, while graphql-go prioritizes type safety and performance. The choice between them depends on project requirements and developer preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

graphql CircleCI Go Reference Coverage Status Join the chat at https://gitter.im/graphql-go/graphql

An implementation of GraphQL in Go. Follows the official reference implementation graphql-js.

Supports: queries, mutations & subscriptions.

Documentation

godoc: https://pkg.go.dev/github.com/graphql-go/graphql

Getting Started

To install the library, run:

go get github.com/graphql-go/graphql

The following is a simple example which defines a schema with a single hello string-type field and a Resolve method which returns the string world. A GraphQL query is performed against this schema with the resulting output printed in JSON format.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/graphql-go/graphql"
)

func main() {
	// Schema
	fields := graphql.Fields{
		"hello": &graphql.Field{
			Type: graphql.String,
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				return "world", 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)
	}

	// Query
	query := `
		{
			hello
		}
	`
	params := graphql.Params{Schema: schema, RequestString: query}
	r := graphql.Do(params)
	if len(r.Errors) > 0 {
		log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
	}
	rJSON, _ := json.Marshal(r)
	fmt.Printf("%s \n", rJSON) // {"data":{"hello":"world"}}
}

For more complex examples, refer to the examples/ directory and graphql_test.go.

Third Party Libraries

NameAuthorDescription
graphql-go-handlerHafiz IsmailMiddleware to handle GraphQL queries through HTTP requests.
graphql-relay-goHafiz IsmailLib to construct a graphql-go server supporting react-relay.
golang-relay-starter-kitHafiz IsmailBarebones starting point for a Relay application with Golang GraphQL server.
dataloaderNick RandallDataLoader implementation in Go.

Blog Posts