GraphQL JSON to Go struct



我有一个看起来像这样的 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",依此类推。 您调用的库实际上非常小。 给定传统的 HTTP 传输格式,它使用普通encoding/json解码来解码响应。 无论您提供什么结构,都需要能够解组"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 正文的示例,尽管不是您提到的库。

我建议使用地图和json包。

我不熟悉 graphQL,所以我会发出一个常规的 HTTP 请求,希望您可以使用它来理解您自己的问题:

response, err := http.Get("https://example.com")
// error checking code omitted
defer response.Body.Close()
// now we want to read the body, easiest way is with the ioutil package,
// this should work with the graphQL response body assuming it satisfies
// the io.Reader interface. This gets us the response body as a byte slice
body, err := ioutil.ReadAll(response.Body)
// next make a destination map, interface can be used in place of string or int
// if you need multiple types
jsonResult := map[string]string{"uuid": ""}
// finally, we use json.Unmarshal to write our byte slice into the map
err = json.Unmarshal(body, &jsonResult)
// now you can access your UUID
fmt.Println(jsonResult["uuid"])

我假设 REST 响应和 graphQL 响应是相似的,如果不是这种情况,请告诉我请求正文的类型,我可以帮助您找出更合适的解决方案。

最新更新