GraphQL JSON 到 Go 结构
时间:2024-04-14
浏览:124
作者:佚名
各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《GraphQL JSON 到 Go 结构》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!
我有一个如下所示的 graphql 查询:
{
actor {
entitysearch(query: "name like 'some_name'") {
results {
entities {
guid
}
}
}
}
}
我不知道如何创建 go 结构来保存返回的数据。我唯一关心的是返回的 guid 字段。
这显然行不通:
type graphqlresponse struct {
guid string
}
有什么帮助吗?或者有没有一种方法可以简单地获取 guid 并将其存储在没有结构的字符串中?
这是完整的代码。我没有收到错误,但 guid 是一个空字符串:
package main
import (
"context"
"fmt"
"log"
"github.com/machinebox/graphql"
)
func main() {
type graphQlResponse struct {
guid string
}
// create a client (safe to share across requests)
client := graphql.NewClient("GraphQL EndPoint")
// make a request
req := graphql.NewRequest(`
{
actor {
entitySearch(query: "name LIKE 'SOME_NAME'") {
results {
entities {
guid
}
}
}
}
}
`)
// set any variables
//req.Var("key", "value")
// set header fields
//req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("API-Key", "KEY_HERE")
// define a Context for the request
ctx := context.Background()
// run it and capture the response
var respData graphQlResponse
if err := client.Run(ctx, req, &respData); err != nil {
log.Fatal(err)
}
fmt.Println(respData.guid)
}解决方案
在 graphql 中,返回的 json 的形状将与 graphql 查询的形状匹配:您将有一个 "data" 字段,该字段将有一个 "actor" 子字段,其中将包含 "entitysearch" 等。您所调用的库实际上非常小。给定 the conventional HTTP transport format,需要 uses ordinary encoding/json decoding 来解码响应。无论您提供什么结构,都需要能够解组 "data" 字段。
这意味着您需要创建一组反映 json 格式的嵌套结构,进而反映您的 graphql 查询:
type Entity struct {
Guid string `json:"guid"`
}
type Result struct {
Entities Entity `json:"entities"`
}
type EntitySearch struct {
Results Result `json:"results"`
}
type Actor struct {
EntitySearch EntitySearch `json:"entitySearch"`
}
type Response struct {
Actor Actor `json:"actor"`
}
fmt.Println(resp.Actor.EntitySearch.Results.Entities.Guid)
https://play.golang.org/p/ENCIjtfAJif 有一个使用此结构和人工 json 主体的示例,尽管不是您提到的库。
本篇关于《GraphQL JSON 到 Go 结构》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
