91 lines
1.6 KiB
Go
91 lines
1.6 KiB
Go
package myAliMarket
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/url"
|
|
)
|
|
|
|
type Client struct {
|
|
url string
|
|
appCode string
|
|
param map[string]string
|
|
fullUrl string
|
|
response string
|
|
}
|
|
|
|
func New(url string, appCode string) *Client {
|
|
return &Client{
|
|
url: url,
|
|
appCode: appCode,
|
|
}
|
|
}
|
|
|
|
func (t *Client) SetParam(param map[string]string) {
|
|
t.param = param
|
|
}
|
|
|
|
func (t *Client) getFullUrl() (string, error) {
|
|
u, err := url.Parse(t.url)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
q := u.Query()
|
|
for k, v := range t.param {
|
|
q.Add(k, v)
|
|
}
|
|
u.RawQuery = q.Encode()
|
|
t.fullUrl = u.String()
|
|
return t.fullUrl, nil
|
|
}
|
|
|
|
func (t *Client) GetFullUrl() string {
|
|
return t.fullUrl
|
|
}
|
|
|
|
func (t *Client) GetResponse() string {
|
|
return t.response
|
|
}
|
|
|
|
func (t *Client) GetRequest(respData interface{}) error {
|
|
fullUrl, err := t.getFullUrl()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
client := &http.Client{}
|
|
request, err := http.NewRequest("GET", fullUrl, nil)
|
|
if err != nil {
|
|
return errors.New("http客户端初始化失败")
|
|
}
|
|
request.Header.Add("Authorization", fmt.Sprintf("APPCODE %s", t.appCode))
|
|
|
|
response, err := client.Do(request)
|
|
if err != nil {
|
|
return errors.New("认证服务器连接失败1")
|
|
}
|
|
|
|
defer response.Body.Close()
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
return errors.New("认证服务器连接失败2")
|
|
}
|
|
|
|
var response2 []byte
|
|
response2, err = ioutil.ReadAll(response.Body)
|
|
if err != nil {
|
|
return errors.New("数据解析失败")
|
|
}
|
|
|
|
t.response = string(response2)
|
|
|
|
err = json.Unmarshal(response2, respData)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|