http_client.go 1.2 KB
package k3cloud

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

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

func (hClient *HttpClient) PostRequest(api string, param interface{}) (*http.Response, error) {
	var err error
	data := param
	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
}