我们正在使用斜杠 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
}
}
}
有任何帮助吗?
最佳答案
您可以使用此包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))
关于go - HTTP请求: golang with graphQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66931228/