## File: README.md

# graphql [](https://circleci.com/gh/graphql-go/graphql/tree/master) [](https://pkg.go.dev/github.com/graphql-go/graphql) [](https://coveralls.io/github/graphql-go/graphql?branch=master) [](https://gitter.im/graphql-go/graphql?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

An implementation of GraphQL in Go. Follows the official reference implementation [`graphql-js`](https://github.com/graphql/graphql-js).

Supports: queries, mutations & subscriptions.

### Documentation

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

### Contribute Back

Friendly reminder links are available in case you would like to contribute back into our commitment with Go and open-source.

| Author        |  PayPal Link  |
|:-------------:|:-------------:|
| [Hafiz Ismail](https://github.com/sogko) | Not available yet. |
| [Chris Ramón](https://github.com/chris-ramon) | https://www.paypal.com/donate/?hosted_button_id=WHUQQYEMTRQBJ |

### Getting Started

To install the library, run:
```bash
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.

```go
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/](https://github.com/graphql-go/graphql/tree/master/examples/) directory and [graphql_test.go](https://github.com/graphql-go/graphql/blob/master/graphql_test.go).

### Third Party Libraries
| Name          | Author        | Description  |
|:-------------:|:-------------:|:------------:|
| [graphql-go-handler](https://github.com/graphql-go/graphql-go-handler) | [Hafiz Ismail](https://github.com/sogko) | Middleware to handle GraphQL queries through HTTP requests. |
| [graphql-relay-go](https://github.com/graphql-go/graphql-relay-go) | [Hafiz Ismail](https://github.com/sogko) | Lib to construct a graphql-go server supporting react-relay. |
| [golang-relay-starter-kit](https://github.com/sogko/golang-relay-starter-kit) | [Hafiz Ismail](https://github.com/sogko) | Barebones starting point for a Relay application with Golang GraphQL server. |
| [dataloader](https://github.com/nicksrandall/dataloader) | [Nick Randall](https://github.com/nicksrandall) | [DataLoader](https://github.com/facebook/dataloader) implementation in Go. |

### Blog Posts
- [Golang + GraphQL + Relay](https://wehavefaces.net/learn-golang-graphql-relay-1-e59ea174a902)

---

## File: examples/todo/README.md

# Go GraphQL ToDo example

An example that consists of basic core GraphQL queries and mutations.

To run the example navigate to the example directory by using your shell of choice.

```
cd examples/todo
```

Run the example, it will spawn a GraphQL HTTP endpoint

```
go run main.go
```

Execute queries via shell.

```
// To get single ToDo item by ID
curl -g 'http://localhost:8080/graphql?query={todo(id:"b"){id,text,done}}'

// To create a ToDo item
curl -g 'http://localhost:8080/graphql?query=mutation+_{createTodo(text:"My+new+todo"){id,text,done}}'

// To get a list of ToDo items
curl -g 'http://localhost:8080/graphql?query={todoList{id,text,done}}'

// To update a ToDo
curl -g 'http://localhost:8080/graphql?query=mutation+_{updateTodo(id:"b",text:"My+new+todo+updated",done:true){id,text,done}}'
```

## Web App

Access the web app at `http://localhost:8080/`. It is work in progress and currently is simply loading todos by using jQuery ajax call.

---

## File: examples/sql-nullstring/README.md

# Go GraphQL SQL null string example

<a target="_blank" rel="noopener noreferrer" href="https://golang.org/pkg/database/sql/#NullString">database/sql Nullstring</a> implementation, with JSON marshalling interfaces.

To run the program, go to the directory  
`cd examples/sql-nullstring`

Run the example  
`go run main.go`

## sql.NullString

On occasion you will encounter sql fields that are nullable, as in

```sql
CREATE TABLE persons (
    id INT PRIMARY KEY,
    name TEXT NOT NULL,
    favorite_dog TEXT -- this field can have a NULL value
)
```

For the struct

```golang
import "database/sql"

type Person struct {
    ID          int             `json:"id" sql:"id"`
    Name        string          `json:"name" sql:"name"`
    FavoriteDog sql.NullString  `json:"favorite_dog" sql:"favorite_dog"`
}
```

But `graphql` would render said field as an object `{{ false}}` or `{{Bulldog true}}`, depending on their validity.

With this implementation, `graphql` would render the null items as an empty string (`""`), but would be saved in the database as `NULL`, appropriately.

The pattern can be extended to include other `database/sql` null types.

---

## File: examples/httpdynamic/README.md

Basically, if we have `data.json` like this:

    [
      { "id": "1", "name": "Dan" },
      { "id": "2", "name": "Lee" },
      { "id": "3", "name": "Nick" }
    ]

... and `go run main.go`, we can query records:

	$ curl -g 'http://localhost:8080/graphql?query={user(name:"Dan"){id}}'
	{"data":{"user":{"id":"1"}}}

... now let's give Dan a surname:

    [
      { "id": "1", "name": "Dan", "surname": "Jones" },
      { "id": "2", "name": "Lee" },
      { "id": "3", "name": "Nick" }
    ]

... and kick the server:

    kill -SIGUSR1 52114

And ask for Dan's surname:

	$ curl -g 'http://localhost:8080/graphql?query={user(name:"Dan"){id,surname}}'
	{"data":{"user":{"id":"1","surname":"Jones"}}}

... or ask Jones's name and ID:

    $ curl -g 'http://localhost:8080/graphql?query={user(surname:"Jones"){id,name}}'
    {"data":{"user":{"id":"1","name":"Dan"}}}

If you look at `main.go`, the file is not field-aware. That is, all it knows is
how to work with `[]map[string]string` type.

With this, we are not that far from exposing dynamic fields and filters which
fully depend on what we have stored, all without changing our tooling.

---

## File: examples/crud/Readme.md

# Go GraphQL CRUD example

Implement create, read, update and delete on Go.

To run the program:

1. go to the directory: `cd examples/crud`
2. Run the example: `go run main.go`

## Create

`http://localhost:8080/product?query=mutation+_{create(name:"Inca Kola",info:"Inca Kola is a soft drink that was created in Peru in 1935 by British immigrant Joseph Robinson Lindley using lemon verbena (wiki)",price:1.99){id,name,info,price}}`

## Read

* Get single product by id: `http://localhost:8080/product?query={product(id:1){name,info,price}}`
* Get product list: `http://localhost:8080/product?query={list{id,name,info,price}}`

## Update

`http://localhost:8080/product?query=mutation+_{update(id:1,price:3.95){id,name,info,price}}`

## Delete

`http://localhost:8080/product?query=mutation+_{delete(id:1){id,name,info,price}}`