我有一个如下所示的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)
}
发布于 2019-09-20 09:28:41
在GraphQL中,返回的JSON的形状将与GraphQL查询的形状相匹配:您将拥有一个"data"
字段,该字段将具有一个包含"entitySearch"
的"actor"
子级,依此类推。你调用的库实际上是非常小的。在给定the conventional HTTP transport format的情况下,它使用uses ordinary encoding/json
decoding来解码响应。无论您提供什么结构,都需要能够解组"data"
字段。
这意味着您需要创建一组映射JSON格式的嵌套结构,而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主体的示例,尽管不是您提到的库。
发布于 2019-09-20 03:28:55
我建议使用地图和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响应类似,如果不是这样,请让我知道请求体的类型,我可以帮助您找到更合适的解决方案。
https://stackoverflow.com/questions/58017536
复制相似问题