123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- package client
- import (
- "git.sxidc.com/go-tools/utils/http_client"
- "time"
- )
- const (
- defaultTimeoutSec = 30
- )
- var instance *Client
- func InitInstance(timeout time.Duration) {
- if instance == nil {
- if timeout == 0 {
- timeout = defaultTimeoutSec * time.Second
- }
- instance = New(timeout)
- }
- }
- func GetInstance() *Client {
- if instance == nil {
- panic("还没有调用InitInstance")
- }
- return instance
- }
- type Client struct {
- client *http_client.Client
- timeout time.Duration
- }
- func New(timeout time.Duration) *Client {
- client := http_client.New()
- return &Client{
- client: client,
- timeout: timeout,
- }
- }
- func (c *Client) post(token string, url string, request interface{}, result interface{}) error {
- req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout))
- resp, err := req.Post(url, request,
- http_client.WithRequestHeaders(map[string]string{
- "Content-Type": "application/json",
- "Authorization": token,
- }))
- if err != nil {
- return err
- }
- err = resp.Json(result)
- if err != nil {
- return err
- }
- return nil
- }
- func (c *Client) delete(token string, url string, queryMap map[string]string, result interface{}) error {
- req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout))
- resp, err := req.Delete(url,
- http_client.WithRequestHeaders(map[string]string{
- "Content-Type": "application/json",
- "Authorization": token,
- }),
- http_client.WithRequestQueryParams(queryMap))
- if err != nil {
- return err
- }
- err = resp.Json(result)
- if err != nil {
- return err
- }
- return nil
- }
- func (c *Client) put(token string, url string, request interface{}, result interface{}) error {
- req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout))
- resp, err := req.Put(url, request,
- http_client.WithRequestHeaders(map[string]string{
- "Content-Type": "application/json",
- "Authorization": token,
- }))
- if err != nil {
- return err
- }
- err = resp.Json(result)
- if err != nil {
- return err
- }
- return nil
- }
- func (c *Client) get(token string, url string, queryMap map[string]string, result interface{}) error {
- req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout))
- resp, err := req.Get(url,
- http_client.WithRequestHeaders(map[string]string{
- "Content-Type": "application/json",
- "Authorization": token,
- }),
- http_client.WithRequestQueryParams(queryMap))
- if err != nil {
- return err
- }
- err = resp.Json(result)
- if err != nil {
- return err
- }
- return nil
- }
|