http_client.go 1.6 KB
package k3cloud

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"github.com/google/uuid"
)

//全局使用的http请求
type HttpClient struct {
	HostUrl string
	Cookie  []*http.Cookie
}

//WrapPostData 包装发送的数据
func (hClient *HttpClient) WrapPostData(param interface{}) (*postData, error) {
	data := postData{
		Format:     1,
		Useragent:  "ApiClient",
		Rid:        uuid.NewString(),
		Timestamp:  time.Now().Format("2006-01-02"),
		V:          "1.0",
		Parameters: param,
	}
	return &data, nil
}

func (hClient *HttpClient) PostRequest(api string, param interface{}) (*http.Response, error) {
	data, err := hClient.WrapPostData(param)
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("%s%s", hClient.HostUrl, api)
	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	err = encoder.Encode(data)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(http.MethodPost, url, &buf)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	for i := range hClient.Cookie {
		req.AddCookie(hClient.Cookie[i])
	}
	client := http.Client{
		Timeout: 60 * time.Second,
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	return resp, err
}

func (hClient *HttpClient) DecodeJSON(r io.Reader, v interface{}) error {
	defer io.Copy(io.Discard, r)
	return json.NewDecoder(r).Decode(v)
}

func (hClient *HttpClient) InvokeApi(api string, param interface{}, respData interface{}) error {
	resp, err := hClient.PostRequest(api, param)
	if err != nil {
		return err
	}
	err = hClient.DecodeJSON(resp.Body, respData)
	return err
}