I am building a service in Go that queries a Magento API.
I already have the oauth credentials needed to make the request (these are persistent) and am able to successfully query the API in Postman.
I am trying to query the Magento API using this package, however every time I make the request I get an error:
Service temporary unavailable
I have searched around and it looks like this is a common error to get when the request does not have a header for Accept: application/json
.
I am using this package to sign my requests currently and cannot see any way to add this header. I am open to using a different package if required, it just needs to support oauth1 authentication.
Being relatively new to Go, I’m not too sure how to add the header to my request and would love some help.
This is my current code:
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/dghubble/oauth1"
)
func main() {
config := oauth1.NewConfig("consumer key", "consumer secret")
token := oauth1.NewToken("token key", "token secret")
httpClient := config.Client(oauth1.NoContext, token)
path := "https://www.example.com/api/rest/customers?limit=2&order=created_at&dir=DESC"
resp, err := httpClient.Get(path)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Raw Resonse Body:n%vn", string(body))
}
How can I add the Accept: application/json
header to my request?
2
Answers
I finally have this working after countless hours spent on it - I swapped the oauth package from dghubble/oauth1 to nhjk/oauth.
This uses the native Go
http
package and so we can set headers like normal, and as outlined by @AlexEfimov.Working code as below:
Create a request:
Set the headers:
Run the request using client as configured in the question:
Example that worked for me:
Output: