简体   繁体   English

HTTP 请求:带有 graphQL 的 golang?

[英]HTTP requests: golang with graphQL?

We are using slash graphql and I can write basic queries like:我们正在使用斜杠 graphql,我可以编写基本查询,例如:

query{
    queryUser{
      user{
         username}
      }
}

jsonData := `{
        query: 
            { 
                queryUser {
                    username
                }
            }
    }`

request, err := http.NewRequest("POST", "https://<GRAPHQL_API_HERE>", []byte(jsonData))

But I dont know how to write this kind of query.但我不知道如何编写这种查询。

mutation addAuthor($author: [AddAuthorInput!]!) {
  addAuthor(input: $author) {
    author {
      id
      name
    }
  }
}

Any help is appreciated?任何帮助表示赞赏?

You can use this package github.com/machinebox/graphql .您可以使用此 package github.com/machinebox/graphql Just provide your query in string.只需在字符串中提供您的查询。

// create a client (safe to share across requests)
client := graphql.NewClient("https://<GRAPHQL_API_HERE>")

// make a request
req := graphql.NewRequest(`
    query ($key: String!) {
        items (id:$key) {
            field1
            field2
            field3
        }
    }
`)

// set any variables
req.Var("key", "value")

// run it and capture the response
var respData ResponseStruct
if err := client.Run(ctx, req, &respData); err != nil {
    log.Fatal(err)
}

[Note] Code borrowed from documentation. [注意] 从文档中借用的代码。

For your case request must be对于您的案例请求必须是

req := graphql.NewRequest(fmt.Sprintf(`
mutation addAuthor($author: [%s!]!) {
  addAuthor(input: $author) {
    author {
      id
      name
     }
    }
   }
 `,stringAuthorInput))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM