dongpang1898 2019-09-19 19:05
浏览 139

GraphQL JSON转Go结构

I have a GraphQL query that looks like this:

{
    actor {
      entitySearch(query: "name LIKE 'SOME_NAME'") {
        results {
          entities {
            guid
          }
        }
      }
    }
  }

I can't figure out how to create the Go struct to hold the returned data. The only thing I care about is the guid field that gets returned.

This clearly doesn't work:

type graphQlResponse struct {
    guid string
}

Any help? Or is there a way I can simply get the guid and store it in a string without a struct?

Here is the whole code. I don't get an error, but guid is an empty string:

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)
}
  • 写回答

2条回答 默认 最新

  • dtdsbakn210537 2019-09-19 19:28
    关注

    I suggest using a map and the json package.

    I am unfamiliar with graphQL so I'll make a regular HTTP request and hope you can use it to make sense of your own issue:

    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"])
    

    I assume that a REST response and a graphQL response are similar, if that's not the case let me know what type the request body is and I can help you figure out a better fitting solution.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化