1

我们正在使用斜杠 graphql,我可以编写基本查询,例如:

query{
    queryUser{
      user{
         username}
      }
}

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

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

但我不知道如何编写这种查询。

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

任何帮助表示赞赏?

4

1 回答 1

0

你可以使用这个包github.com/machinebox/graphql。只需在字符串中提供您的查询。

// 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)
}

[注意] 从文档中借用的代码。

对于您的案例请求必须是

req := graphql.NewRequest(fmt.Sprintf(`
mutation addAuthor($author: [%s!]!) {
  addAuthor(input: $author) {
    author {
      id
      name
     }
    }
   }
 `,stringAuthorInput))
于 2021-04-03T14:46:50.940 回答