go - HTTP请求: golang with graphQL?

标签 go graphql dgraph

我们正在使用斜杠 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/

相关文章:

php - 如何在文件夹包含的每个HTML文件中包含单独的头文件?

go - 为项目使用多个包与单个包

go - 带有Websocket和Redis的多房间聊天应用程序

graphql - 添加 Enum 值对 GraphQL 来说是一个重大变化吗?

go - RPC 错误 : code = Unavailable desc = connection closed in Go code

json - 在 JSON get 请求中设置 header

javascript - 查询时 GraphiQL 返回 'null'

reactjs - 如何限制 useQuery 的 api 调用只能调用一次?

graphql - 如何分组和计算dgraph

graph-databases - 分片图形数据库