简体   繁体   中英

HTTP requests: golang with graphQL?

We are using slash graphql and I can write basic queries like:

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 . 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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