User Tools

Site Tools


GraphQL in Golang sample

Server

server.go
/*
 * Copyright 2020 Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "github.com/gin-gonic/gin"
    "goql/controller"
)
 
func main() {
    gin.DisableConsoleColor()
    gin.SetMode(gin.ReleaseMode)
    router := gin.Default()
    controller := controller.New()
    router.GET("/hello", controller.Hello)
    router.POST("/query", controller.GraphQL)
    router.Run()
}
controller.go
/*
 * Copyright 2020 Oleg Borodin  <borodin@unix7.org>
 */
 
package controller
 
import (
    "net/http"
    "context"
    "fmt"
    "github.com/gin-gonic/gin"
 
    graphql "github.com/graph-gophers/graphql-go"
    relay   "github.com/graph-gophers/graphql-go/relay"
)
 
 
type HelloResolver struct{
}
 
func (this *HelloResolver) Hello(ctx context.Context, args struct{ Id int32 }) (string, error) {
    return fmt.Sprintf("hello #id %d", args.Id), nil
}
 
var schemaDesr = `
    schema {
        query: Query
    }
    type Query {
        hello(id: Int!): String!
    }
`
 
type Controller struct{
}
 
func (this *Controller) GraphQL(context *gin.Context){
    schema := graphql.MustParseSchema(schemaDesr, &HelloResolver{})
 
    relay := &relay.Handler{Schema: schema}
    relay.ServeHTTP(context.Writer, context.Request)
}
 
func New() *Controller {
    return &Controller{
    }
}

Client

client.go
/*
 * Copyright 2020 Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)
 
func main() {
    query := map[string]string{
        "query": `
            {
                hello(id: 5) {
                }
            }
        `,
    }
    queryJson, _ := json.Marshal(query)
    request, err := http.NewRequest("POST", "http://localhost:8080/query", bytes.NewBuffer(queryJson))
    client := &http.Client{Timeout: time.Second * 10}
    response, err := client.Do(request)
    defer response.Body.Close()
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    data, _ := ioutil.ReadAll(response.Body)
    fmt.Println(string(data))
}

Out

$ ./client
{"data":{"hello":"hello #id 5"}}

Client2

client2.go
/*
 * Copyright 2020 Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "context"
    "fmt"
 
    "github.com/machinebox/graphql"
)
 
func main() {
    graphqlClient := graphql.NewClient("http://localhost:8080/query")
    graphqlRequest := graphql.NewRequest(`
        {
            hello(id: 5) {
            }
        }
    `)
    var graphqlResponse interface{}
    if err := graphqlClient.Run(context.Background(), graphqlRequest, &graphqlResponse); err != nil {
        panic(err)
    }
    fmt.Println(graphqlResponse)
}

Out

$ ./client2
map[hello:hello #id 5]

First PagePrevious PageBack to overviewNext PageLast Page