Asana Integeration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

190 lines
3.8 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package util
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. //"fmt"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "time"
  11. "git.drinkme.beer/yinghe/log"
  12. )
  13. // Network contains common configuration.
  14. type Network struct {
  15. Env string `toml:"env"`
  16. Host []string `toml:"gateway"`
  17. GatewayURL string
  18. RequestTimeout time.Duration `toml:"request_timeout"`
  19. ConnectTimeout time.Duration `toml:"connect_timeout"`
  20. SocketTimeout time.Duration `toml:"socket_timeout"`
  21. }
  22. var network = Network{
  23. RequestTimeout: 45 * time.Second,
  24. ConnectTimeout: 45 * time.Second,
  25. SocketTimeout: 55 * time.Second,
  26. }
  27. var client = &http.Client{
  28. Transport: &http.Transport{
  29. DialContext: func(ctx context.Context, n, addr string) (net.Conn, error) {
  30. conn, err := net.DialTimeout(n, addr,
  31. time.Second*network.RequestTimeout,
  32. )
  33. if err != nil {
  34. return conn, err
  35. }
  36. conn.SetDeadline(time.Now().
  37. Add(time.Second * network.ConnectTimeout))
  38. return conn, err
  39. },
  40. ResponseHeaderTimeout: time.Second * network.SocketTimeout,
  41. MaxConnsPerHost: 20,
  42. IdleConnTimeout: 3 * time.Minute,
  43. MaxIdleConns: 10,
  44. //Proxy: func(_ *http.Request) (*url.URL, error) {
  45. // return url.Parse("http://192.168.0.104:1087")
  46. //},
  47. },
  48. }
  49. func SetNetworkCfg(cfg Network) {
  50. if 0 < cfg.RequestTimeout {
  51. network.RequestTimeout = cfg.RequestTimeout
  52. }
  53. if 0 < cfg.ConnectTimeout {
  54. network.ConnectTimeout = cfg.ConnectTimeout
  55. }
  56. if 0 < cfg.SocketTimeout {
  57. network.SocketTimeout = cfg.SocketTimeout
  58. }
  59. }
  60. type Body interface {
  61. BuildRequest() []byte
  62. }
  63. type Client struct {
  64. GatewayURL string
  65. URI string
  66. Headers map[string]string
  67. Authorization string
  68. Method string
  69. HTTPStatus int
  70. Body []byte // Indicates both Request Body & Response Body
  71. TraceId interface{}
  72. //Buffer *bufio.Reader
  73. }
  74. func (c *Client) AddHeader(k, v string) {
  75. c.Headers[k] = v
  76. }
  77. func (c *Client) Print() {
  78. if nil != c.Body {
  79. log.Infof(string(c.Body))
  80. } else {
  81. log.Infof("nil")
  82. }
  83. }
  84. type Bytes []byte
  85. func (self Bytes) BuildRequest() []byte {
  86. return self
  87. }
  88. /*
  89. url, uri, method, body
  90. */
  91. func NewHttpClient(url, uri, m string, b []byte) *Client {
  92. return &Client{
  93. GatewayURL: url,
  94. URI: uri,
  95. Method: m,
  96. Headers: make(map[string]string),
  97. Body: b,
  98. }
  99. }
  100. func (c *Client) BuildRequest(body Body) {
  101. if nil == c.Body {
  102. c.Body = make([]byte, 0, 1024)
  103. }
  104. c.Body = append(c.Body, body.BuildRequest()...)
  105. }
  106. func (c *Client) Request() (err error) {
  107. log.Infof("request url: %s", c.GatewayURL+c.URI)
  108. request, err := http.NewRequest(c.Method,
  109. c.GatewayURL+c.URI,
  110. bytes.NewReader(c.Body),
  111. )
  112. if err != nil {
  113. log.Info("Post err occurs:", err.Error())
  114. return
  115. }
  116. for k, v := range c.Headers {
  117. request.Header.Set(k, v)
  118. }
  119. resp, err := client.Do(request)
  120. if nil == resp {
  121. log.Info("none response received")
  122. err = errors.New("none response received")
  123. return
  124. }
  125. defer resp.Body.Close()
  126. c.HTTPStatus = resp.StatusCode
  127. c.Body, err = ioutil.ReadAll(resp.Body)
  128. return
  129. }
  130. func Request(req *http.Request) ([]byte, error) {
  131. var (
  132. err error
  133. body []byte
  134. )
  135. if nil == req {
  136. log.Errorf("illegal request")
  137. return nil, errors.New("illegal request")
  138. }
  139. //log.Infof("%v", req)
  140. resp, err := client.Do(req)
  141. if nil == resp {
  142. log.Info("none response received")
  143. err = errors.New("none response received")
  144. return nil, err
  145. }
  146. defer resp.Body.Close()
  147. if http.StatusOK != resp.StatusCode {
  148. if nil != resp.Body {
  149. body, _ = ioutil.ReadAll(resp.Body)
  150. log.Infof("response: %s", string(body))
  151. }
  152. log.Errorf("unexpected status: %d", resp.StatusCode)
  153. return nil, errors.New("unexpected status")
  154. }
  155. body, err = ioutil.ReadAll(resp.Body)
  156. if nil != err {
  157. log.Errorf("invalid response body: %s", err.Error())
  158. return nil, err
  159. }
  160. log.Infof("response: %s", string(body))
  161. return body, nil
  162. }