httplib.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package jpushclient
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "encoding/xml"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "strings"
  14. "time"
  15. )
  16. // Get returns *HttpRequest with GET method.
  17. func Get(url string) *HttpRequest {
  18. var req http.Request
  19. req.Method = "GET"
  20. req.Header = http.Header{}
  21. return &HttpRequest{url, &req, map[string]string{}, 60 * time.Second, 60 * time.Second, nil, nil, nil}
  22. }
  23. // Post returns *HttpRequest with POST method.
  24. func Post(url string) *HttpRequest {
  25. var req http.Request
  26. req.Method = "POST"
  27. req.Header = http.Header{}
  28. return &HttpRequest{url, &req, map[string]string{}, 60 * time.Second, 60 * time.Second, nil, nil, nil}
  29. }
  30. func Delete(url string) *HttpRequest {
  31. var req http.Request
  32. req.Method = "DELETE"
  33. req.Header = http.Header{}
  34. return &HttpRequest{url, &req, map[string]string{}, 60 * time.Second, 60 * time.Second, nil, nil, nil}
  35. }
  36. // HttpRequest provides more useful methods for requesting one url than http.Request.
  37. type HttpRequest struct {
  38. url string
  39. req *http.Request
  40. params map[string]string
  41. connectTimeout time.Duration
  42. readWriteTimeout time.Duration
  43. tlsClientConfig *tls.Config
  44. proxy func(*http.Request) (*url.URL, error)
  45. transport http.RoundTripper
  46. }
  47. // SetTimeout sets connect time out and read-write time out for Request.
  48. func (b *HttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *HttpRequest {
  49. b.connectTimeout = connectTimeout
  50. b.readWriteTimeout = readWriteTimeout
  51. return b
  52. }
  53. func (b *HttpRequest) SetBasicAuth(userName, password string) *HttpRequest {
  54. b.req.SetBasicAuth(userName, password)
  55. return b
  56. }
  57. // SetTLSClientConfig sets tls connection configurations if visiting https url.
  58. func (b *HttpRequest) SetTLSClientConfig(config *tls.Config) *HttpRequest {
  59. b.tlsClientConfig = config
  60. return b
  61. }
  62. // Header add header item string in request.
  63. func (b *HttpRequest) Header(key, value string) *HttpRequest {
  64. b.req.Header.Set(key, value)
  65. return b
  66. }
  67. // Set the protocol version for incoming requests.
  68. // Client requests always use HTTP/1.1.
  69. func (b *HttpRequest) SetProtocolVersion(vers string) *HttpRequest {
  70. if len(vers) == 0 {
  71. vers = "HTTP/1.1"
  72. }
  73. major, minor, ok := http.ParseHTTPVersion(vers)
  74. if ok {
  75. b.req.Proto = vers
  76. b.req.ProtoMajor = major
  77. b.req.ProtoMinor = minor
  78. }
  79. return b
  80. }
  81. // SetCookie add cookie into request.
  82. func (b *HttpRequest) SetCookie(cookie *http.Cookie) *HttpRequest {
  83. b.req.Header.Add("Cookie", cookie.String())
  84. return b
  85. }
  86. // Set transport to
  87. func (b *HttpRequest) SetTransport(transport http.RoundTripper) *HttpRequest {
  88. b.transport = transport
  89. return b
  90. }
  91. // Set http proxy
  92. // example:
  93. //
  94. // func(req *http.Request) (*url.URL, error) {
  95. // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
  96. // return u, nil
  97. // }
  98. func (b *HttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *HttpRequest {
  99. b.proxy = proxy
  100. return b
  101. }
  102. // Param adds query param in to request.
  103. // params build query string as ?key1=value1&key2=value2...
  104. func (b *HttpRequest) Param(key, value string) *HttpRequest {
  105. b.params[key] = value
  106. return b
  107. }
  108. // Body adds request raw body.
  109. // it supports string and []byte.
  110. func (b *HttpRequest) Body(data interface{}) *HttpRequest {
  111. switch t := data.(type) {
  112. case string:
  113. bf := bytes.NewBufferString(t)
  114. b.req.Body = ioutil.NopCloser(bf)
  115. b.req.ContentLength = int64(len(t))
  116. case []byte:
  117. bf := bytes.NewBuffer(t)
  118. b.req.Body = ioutil.NopCloser(bf)
  119. b.req.ContentLength = int64(len(t))
  120. }
  121. return b
  122. }
  123. func (b *HttpRequest) getResponse() (*http.Response, error) {
  124. var paramBody string
  125. if len(b.params) > 0 {
  126. var buf bytes.Buffer
  127. for k, v := range b.params {
  128. buf.WriteString(url.QueryEscape(k))
  129. buf.WriteByte('=')
  130. buf.WriteString(url.QueryEscape(v))
  131. buf.WriteByte('&')
  132. }
  133. paramBody = buf.String()
  134. paramBody = paramBody[0 : len(paramBody)-1]
  135. }
  136. if b.req.Method == "GET" && len(paramBody) > 0 {
  137. if strings.Index(b.url, "?") != -1 {
  138. b.url += "&" + paramBody
  139. } else {
  140. b.url = b.url + "?" + paramBody
  141. }
  142. } else if b.req.Method == "POST" && b.req.Body == nil && len(paramBody) > 0 {
  143. b.Header("Content-Type", "application/x-www-form-urlencoded")
  144. b.Body(paramBody)
  145. }
  146. url, err := url.Parse(b.url)
  147. if url.Scheme == "" {
  148. b.url = "http://" + b.url
  149. url, err = url.Parse(b.url)
  150. }
  151. if err != nil {
  152. return nil, err
  153. }
  154. b.req.URL = url
  155. trans := b.transport
  156. if trans == nil {
  157. // create default transport
  158. trans = &http.Transport{
  159. TLSClientConfig: b.tlsClientConfig,
  160. Proxy: b.proxy,
  161. Dial: TimeoutDialer(b.connectTimeout, b.readWriteTimeout),
  162. }
  163. } else {
  164. // if b.transport is *http.Transport then set the settings.
  165. if t, ok := trans.(*http.Transport); ok {
  166. if t.TLSClientConfig == nil {
  167. t.TLSClientConfig = b.tlsClientConfig
  168. }
  169. if t.Proxy == nil {
  170. t.Proxy = b.proxy
  171. }
  172. if t.Dial == nil {
  173. t.Dial = TimeoutDialer(b.connectTimeout, b.readWriteTimeout)
  174. }
  175. }
  176. }
  177. client := &http.Client{
  178. Transport: trans,
  179. }
  180. resp, err := client.Do(b.req)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return resp, nil
  185. }
  186. // String returns the body string in response.
  187. // it calls Response inner.
  188. func (b *HttpRequest) String() (string, error) {
  189. data, err := b.Bytes()
  190. if err != nil {
  191. return "", err
  192. }
  193. return string(data), nil
  194. }
  195. // Bytes returns the body []byte in response.
  196. // it calls Response inner.
  197. func (b *HttpRequest) Bytes() ([]byte, error) {
  198. resp, err := b.getResponse()
  199. if err != nil {
  200. return nil, err
  201. }
  202. if resp.Body == nil {
  203. return nil, nil
  204. }
  205. defer resp.Body.Close()
  206. data, err := ioutil.ReadAll(resp.Body)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return data, nil
  211. }
  212. // ToFile saves the body data in response to one file.
  213. // it calls Response inner.
  214. func (b *HttpRequest) ToFile(filename string) error {
  215. f, err := os.Create(filename)
  216. if err != nil {
  217. return err
  218. }
  219. defer f.Close()
  220. resp, err := b.getResponse()
  221. if err != nil {
  222. return err
  223. }
  224. if resp.Body == nil {
  225. return nil
  226. }
  227. defer resp.Body.Close()
  228. _, err = io.Copy(f, resp.Body)
  229. if err != nil {
  230. return err
  231. }
  232. return nil
  233. }
  234. // ToJson returns the map that marshals from the body bytes as json in response .
  235. // it calls Response inner.
  236. func (b *HttpRequest) ToJson(v interface{}) error {
  237. data, err := b.Bytes()
  238. if err != nil {
  239. return err
  240. }
  241. err = json.Unmarshal(data, v)
  242. if err != nil {
  243. return err
  244. }
  245. return nil
  246. }
  247. // ToXml returns the map that marshals from the body bytes as xml in response .
  248. // it calls Response inner.
  249. func (b *HttpRequest) ToXML(v interface{}) error {
  250. data, err := b.Bytes()
  251. if err != nil {
  252. return err
  253. }
  254. err = xml.Unmarshal(data, v)
  255. if err != nil {
  256. return err
  257. }
  258. return nil
  259. }
  260. // Response executes request client gets response mannually.
  261. func (b *HttpRequest) Response() (*http.Response, error) {
  262. return b.getResponse()
  263. }
  264. // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
  265. func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
  266. return func(netw, addr string) (net.Conn, error) {
  267. conn, err := net.DialTimeout(netw, addr, cTimeout)
  268. if err != nil {
  269. return nil, err
  270. }
  271. conn.SetDeadline(time.Now().Add(rwTimeout))
  272. return conn, nil
  273. }
  274. }