github.com/gorocks/apikit@v0.0.0-20170808011444-396ab031afbd/apikit.go (about)

     1  package apikit
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"encoding/xml"
     7  	"fmt"
     8  	"io"
     9  	"net/http"
    10  	"net/url"
    11  	"reflect"
    12  	"regexp"
    13  	"strconv"
    14  	"strings"
    15  	"time"
    16  
    17  	"github.com/fatih/structs"
    18  )
    19  
    20  //
    21  const (
    22  	MediaJSON = "application/json;charset=utf-8"
    23  	MediaForm = "application/x-www-form-urlencoded;charset=utf-8"
    24  	MediaXML  = "application/xml;charset=utf-8"
    25  )
    26  
    27  // A Client manages communication with API.
    28  type Client struct {
    29  	client *http.Client
    30  	header map[string]string
    31  }
    32  
    33  // H is a map shortcut.
    34  type H map[string]string
    35  
    36  // NewClient returns a new API client.
    37  func NewClient(httpClient *http.Client) *Client {
    38  	if httpClient == nil {
    39  		httpClient = &http.Client{Timeout: 10 * time.Second}
    40  	}
    41  	c := &Client{client: httpClient, header: H{}}
    42  	return c
    43  }
    44  
    45  // SetHeader sets a header.
    46  func (c *Client) SetHeader(h H) {
    47  	for k, v := range h {
    48  		c.header[k] = v
    49  	}
    50  }
    51  
    52  // AddHeader adds a header mapping.
    53  func (c *Client) AddHeader(key, val string) {
    54  	c.header[key] = val
    55  }
    56  
    57  // NewRequest creates an API request.
    58  func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
    59  	u, err := url.Parse(urlStr)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  
    64  	var buf io.Reader
    65  
    66  	switch ct := c.header["Content-Type"]; ct {
    67  	case MediaJSON:
    68  		if body != nil {
    69  			b, err := json.Marshal(body)
    70  			if err != nil {
    71  				return nil, err
    72  			}
    73  			buf = bytes.NewBuffer(b)
    74  		}
    75  	case MediaForm, "":
    76  		v := url.Values{}
    77  		for k, val := range Params(structs.Map(body)) {
    78  			v.Set(k, val)
    79  		}
    80  		buf = strings.NewReader(v.Encode())
    81  		c.AddHeader("Content-Type", MediaForm)
    82  	case MediaXML:
    83  		if body != nil {
    84  			var b []byte
    85  			b, err := xml.Marshal(body)
    86  			if err != nil {
    87  				return nil, err
    88  			}
    89  			buf = bytes.NewBuffer(b)
    90  		}
    91  	default:
    92  		panic("unsupported content type!")
    93  	}
    94  	req, err := http.NewRequest(method, u.String(), buf)
    95  	if err != nil {
    96  		return nil, err
    97  	}
    98  	if len(c.header) != 0 {
    99  		for k, v := range c.header {
   100  			req.Header.Add(k, v)
   101  		}
   102  	}
   103  	return req, nil
   104  }
   105  
   106  // Do sends an API request and returns the API response.
   107  func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {
   108  	resp, err := c.client.Do(req)
   109  	if err != nil {
   110  		return nil, err
   111  	}
   112  	defer resp.Body.Close()
   113  
   114  	if v != nil {
   115  		if w, ok := v.(io.Writer); ok {
   116  			io.Copy(w, resp.Body)
   117  		} else {
   118  			if r, _ := regexp.MatchString("(plain|xml|xhtml)", resp.Header.Get("Content-Type")); r {
   119  				if err := xml.NewDecoder(resp.Body).Decode(v); err == io.EOF {
   120  					err = nil
   121  				}
   122  			} else {
   123  				if err := json.NewDecoder(resp.Body).Decode(v); err == io.EOF {
   124  					err = nil
   125  				}
   126  			}
   127  		}
   128  	}
   129  	return resp, err
   130  }
   131  
   132  // Params expands a nested map.
   133  func Params(m0 map[string]interface{}) (m map[string]string) {
   134  	if m == nil {
   135  		m = make(map[string]string)
   136  	}
   137  
   138  	for k, v := range m0 {
   139  		val := reflect.ValueOf(v)
   140  		if v == nil {
   141  			continue
   142  		}
   143  		switch val.Kind() {
   144  		case reflect.Map:
   145  			for k, v0 := range Params(v.(map[string]interface{})) {
   146  				m[k] = v0
   147  			}
   148  		case reflect.String:
   149  			if val.Len() != 0 {
   150  				m[k] = v.(string)
   151  			}
   152  		case reflect.Int:
   153  			if v != 0 {
   154  				m[k] = strconv.FormatInt(int64(v.(int)), 10)
   155  			}
   156  		case reflect.Array, reflect.Slice:
   157  			b, _ := json.Marshal(val.Interface())
   158  			m[k] = string(b)
   159  		default:
   160  			panic(fmt.Sprintf("unsupported type: %T", v))
   161  		}
   162  	}
   163  	return
   164  }