Creare un client GraphQL in Go
In questo articolo vediamo come creare un semplice client GraphQL in Dart.
Come "server" useremo QraphQLPlaceholder.
Prima di tutto installiamo le libreria:
go get github.com/machinebox/graphql
Qui sotto un pò di codice; ho messo tutto insieme per comodità:
package main
import (
"context"
"fmt"
"log"
"github.com/machinebox/graphql"
)
type User struct {
ID interface{} `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type UsersResponse struct {
Users []User `json:"users"`
}
func main() {
client := graphql.NewClient("https://graphqlplaceholder.vercel.app/graphql")
req := graphql.NewRequest(`
query ListaUtenti {
users {
id
name
email
}
}
`)
ctx := context.Background()
var response UsersResponse
if err := client.Run(ctx, req, &response); err != nil {
log.Fatal("Errore durante la richiesta: ", err)
}
fmt.Println("Lista Utenti")
for _, user := range response.Users {
fmt.Printf("ID: %v, Nome: %-20s, Email: %sn", user.ID, user.Name, user.Email)
}
}
Enjoy!
go graphql qraphqlplaceholder
Commentami!