package main import ( "github.com/graphql-go/graphql" "github.com/kr/pretty" ) type Todo struct { ID string `json:"id"` Text string `json:"text"` Done bool `json:"done"` } func main() { // define custom GraphQL ObjectType `todoType` for our Golang struct `Todo` // Note that // - the fields in our todoType maps with the json tags for the fields in our struct // - the field type matches the field type in our struct todoType := graphql.NewObject(graphql.ObjectConfig{ Name: "Todo", Fields: graphql.Fields{ "id": &graphql.Field{ Type: graphql.String, }, "text": &graphql.Field{ Type: graphql.String, }, "done": &graphql.Field{ Type: graphql.Boolean, }, }, }) // root mutation rootMutation := graphql.NewObject(graphql.ObjectConfig{ Name: "RootMutation", Fields: graphql.Fields{ "createTodo": &graphql.Field{ Type: todoType, // the return type for this field Args: graphql.FieldConfigArgument{ "text": &graphql.ArgumentConfig{ Type: graphql.NewNonNull(graphql.String), }, }, Resolve: func(params graphql.ResolveParams) interface{} { // marshall and cast the argument value text, _ := params.Args["text"].(string) // perform mutation operation here // for e.g. create a Todo and save to DB. newTodo := &Todo{ ID: "id0001", Text: text, Done: false, } // return the new Todo object that we supposedly save to DB // Note here that // - we are returning a `Todo` struct instance here // - we previously specified the return Type to be `todoType` // - `Todo` struct maps to `todoType`, as defined in `todoType` ObjectConfig` return newTodo }, }, }, }) // root query // we just define a trivial example here, since root query is required. rootQuery := graphql.NewObject(graphql.ObjectConfig{ Name: "RootQuery", Fields: graphql.Fields{ "lastTodo": &graphql.Field{ Type: todoType, }, }, }) // define schema, with our rootQuery and rootMutation schema, err := graphql.NewSchema(graphql.SchemaConfig{ Query: rootQuery, Mutation: rootMutation, }) if err != nil { panic(err) } // our mutation request request := ` mutation _ { newTodo: createTodo(text: "This is a todo mutation example") { text done } } ` // execute query request p := graphql.Params{ Schema: schema, RequestString: request, } result := graphql.Do(p) pretty.Println(result) // Output // &graphql.Result{ // Data: map[string]interface {}{ // "newTodo": map[string]interface {}{ // "text": "This is a todo mutation example", // "done": bool(false), // }, // }, // Errors: nil, // } }