在Go中查询Magento API

huangapple go评论86阅读模式
英文:

Querying Magento API in Go

问题

我正在使用Go构建一个查询Magento API的服务。

我已经拥有了进行请求所需的oauth凭据(这些是持久的),并且能够在Postman中成功查询API。

我正在尝试使用这个包来查询Magento API,但是每次我发出请求时都会收到一个错误:

服务暂时不可用

我已经搜索了一下,看起来当请求没有一个Accept: application/json的头部时,这是一个常见的错误。

我目前正在使用这个包来对我的请求进行签名,但是我没有找到任何添加这个头部的方法。如果需要的话,我可以使用其他的包,只要支持oauth1身份验证即可。

作为一个相对新手,我不太确定如何在我的请求中添加头部,希望能得到一些帮助。

这是我的当前代码:

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%v\n", string(body))
}

我该如何在我的请求中添加 Accept: application/json 头部?

英文:

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%v\n", string(body))
}

How can I add the Accept: application/json header to my request?

答案1

得分: 2

创建一个请求:

req, err := http.NewRequest("GET", path, nil)
if err != nil {
     // 处理错误
}

设置请求头:

req.Header.Add("Accept", "application/json")

使用在问题中配置的客户端运行请求:

resp, err := httpClient.Do(req)
if err != nil {
     // 处理错误
}

对我有效的示例:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"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"
	req, err := http.NewRequest("GET", path, nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Add("Accept", "application/json")

	resp, err := httpClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("原始响应体:\n%v\n", string(body))
}

输出:

原始响应体:
<!doctype html>
<html>
<head>
      <title>Example Domain</title>
      ...
</head>
<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is established to be used for illustrative examples in documents. You may use this
    domain in examples without prior coordination or asking for permission.</p>
    <p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
      ...
英文:

Create a request:

req, err := http.NewRequest(&quot;GET&quot;, path, nil)
if err != nil {
     // handle error
}

Set the headers:

req.Header.Add(&quot;Accept&quot;, &quot;application/json&quot;)

Run the request using client as configured in the question:

resp, err := httpClient.Do(req)
if err != nil {
     // handle error
}

Example that worked for me:

package main

import (
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
	&quot;log&quot;
	&quot;net/http&quot;

	&quot;github.com/dghubble/oauth1&quot;
)

func main() {

	config := oauth1.NewConfig(&quot;consumer key&quot;, &quot;consumer secret&quot;)
	token := oauth1.NewToken(&quot;token key&quot;, &quot;token secret&quot;)

	httpClient := config.Client(oauth1.NoContext, token)

	path := &quot;https://www.example.com/api/rest/customers?limit=2&amp;order=created_at&amp;dir=DESC&quot;
	req, err := http.NewRequest(&quot;GET&quot;, path, nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Add(&quot;Accept&quot;, &quot;application/json&quot;)

	resp, err := httpClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf(&quot;Raw Resonse Body:\n%v\n&quot;, string(body))
}

Output:

Raw Resonse Body:
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
      &lt;title&gt;Example Domain&lt;/title&gt;
      ...
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
    &lt;h1&gt;Example Domain&lt;/h1&gt;
    &lt;p&gt;This domain is established to be used for illustrative examples in documents. You may use this
    domain in examples without prior coordination or asking for permission.&lt;/p&gt;
    &lt;p&gt;&lt;a href=&quot;http://www.iana.org/domains/example&quot;&gt;More information...&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
      ...

答案2

得分: 0

我终于在无数个小时的努力后使其正常工作了 - 我将oauth包从dghubble/oauth1换成了nhjk/oauth

这个代码使用了原生的Go http包,所以我们可以像平常一样设置头部,就像@AlexEfimov所概述的那样。

以下是工作的代码:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/nhjk/oauth"
)

func main() {

	ck := "consumer key"
	cs := "consumer secret"
	tk := "token key"
	ts := "token secret"

	// 创建一个http客户端和一个要发送的请求
	client := new(http.Client)
	req, _ := http.NewRequest("GET", "https://www.example.com/api/rest/customers?limit=2&order=created_at&dir=DESC", nil)

	req.Header.Set("Accept", "application/json")

	// 一个consumer允许您使用令牌对请求进行授权
	cons := oauth.Consumer{ck, cs}

	// 授权请求
	cons.Authorize(req, &oauth.Token{tk, ts})

	// 发送请求并打印响应体
	res, _ := client.Do(req)
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Printf("%s\n", body)
}
英文:

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:

package main

import (
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
	&quot;net/http&quot;

	&quot;github.com/nhjk/oauth&quot;
)

func main() {

	ck := &quot;consumer key&quot;
	cs := &quot;consumer secret&quot;
	tk := &quot;token key&quot;
	ts := &quot;token secret&quot;

	// create an http client and a request for it to send
	client := new(http.Client)
	req, _ := http.NewRequest(&quot;GET&quot;, &quot;https://www.example.com/api/rest/customers?limit=2&amp;order=created_at&amp;dir=DESC&quot;, nil)

	req.Header.Set(&quot;Accept&quot;, &quot;application/json&quot;)

	// a consumer allows you to authorize requests with a token
	cons := oauth.Consumer{ck, cs}

	// authorize request
	cons.Authorize(req, &amp;oauth.Token{tk, ts})

	// send request and print body
	res, _ := client.Do(req)
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Printf(&quot;%s\n&quot;, body)
}

huangapple
  • 本文由 发表于 2017年8月11日 14:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/45628831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定