http_utils.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package utils
  2. import (
  3. "compress/flate"
  4. "compress/gzip"
  5. "compress/zlib"
  6. "context"
  7. "crypto/tls"
  8. "fmt"
  9. "golang.org/x/net/proxy"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "strings"
  16. "time"
  17. )
  18. // Error Code接口
  19. type IErrorCode interface {
  20. // 转换为int
  21. ToInt() int
  22. // 方便与int比较
  23. Equals(errCode int) bool
  24. // 获取错误信息
  25. ErrMsg(args ...interface{}) string
  26. }
  27. type Res struct {
  28. Head ResHead `json:"head"`
  29. Data interface{} `json:"data,omitempty"`
  30. }
  31. type ResHead struct {
  32. ErrCode int `json:"errcode"`
  33. ErrMsg string `json:"errmsg,omitempty"`
  34. Detail string `json:"-"`
  35. HttpStatus int `json:"-"`
  36. }
  37. func E2(errDetail interface{}, errCode IErrorCode, args ...interface{}) *Res {
  38. errMsg := errCode.ErrMsg(args...)
  39. return E(errCode.ToInt(), errMsg, errDetail)
  40. }
  41. func E(status int, errMsg string, errDetail interface{}) *Res {
  42. var msg, detail string
  43. if nil != errDetail {
  44. detail = strings.TrimSpace(fmt.Sprintf("%s", errDetail))
  45. }
  46. msg = strings.TrimSpace(errMsg)
  47. return &Res{
  48. Head: ResHead{
  49. ErrCode: status,
  50. ErrMsg: msg,
  51. Detail: detail,
  52. HttpStatus: http.StatusInternalServerError,
  53. },
  54. }
  55. }
  56. func R(data interface{}) *Res {
  57. return &Res{
  58. Head: ResHead{
  59. ErrCode: 0,
  60. ErrMsg: "",
  61. HttpStatus: http.StatusOK,
  62. },
  63. Data: data,
  64. }
  65. }
  66. // http请求相关默认配置
  67. const (
  68. DefaultHttpDialTimeout = 20 * time.Second
  69. DefaultHttpKeepAlive = 120 * time.Second
  70. DefaultHttpMaxIdleConns = 1000
  71. DefaultHttpMaxIdleConnsPerHost = 1000
  72. DefaultHttpIdleConnTimeout = 90 * time.Second
  73. DefaultHttpTimeout = 30 * time.Second
  74. )
  75. // http请求配置
  76. type RequestPromise struct {
  77. headers http.Header
  78. encoding Charset
  79. timeout time.Duration
  80. proxy func(*http.Request) (*url.URL, error)
  81. dialContext func(ctx context.Context, network, addr string) (net.Conn, error)
  82. client *http.Client
  83. isSkipTls bool
  84. }
  85. // 返回一个http请求配置对象,默认带上压缩头
  86. func NewRequest() *RequestPromise {
  87. return (&RequestPromise{}).
  88. SetHeader("Accept-Encoding", "gzip, deflate, zlib")
  89. }
  90. // 返回一个http请求配置对象,默认带上压缩头和Content-Type = application/json; charset=utf-8
  91. func JSONRequest() *RequestPromise {
  92. return (&RequestPromise{}).
  93. SetHeader("Accept-Encoding", "gzip, deflate, zlib").
  94. SetHeader("Content-Type", "application/json; charset=utf-8")
  95. }
  96. // 返回一个http请求配置对象,默认带上压缩头和Content-Type = application/xml; charset=utf-8
  97. func XMLRequest() *RequestPromise {
  98. return (&RequestPromise{}).
  99. SetHeader("Accept-Encoding", "gzip, deflate, zlib").
  100. SetHeader("Content-Type", "application/xml; charset=utf-8")
  101. }
  102. // 返回一个采用了连接池和Keepalive配置的http client,可以配合RequestPromise的SetClient函数使用
  103. // 默认不使用它,而是每次请求新建连接
  104. func NewPoolingHttpClient() *http.Client {
  105. return &http.Client{
  106. Transport: &http.Transport{
  107. DialContext: (&net.Dialer{
  108. Timeout: DefaultHttpDialTimeout,
  109. KeepAlive: DefaultHttpKeepAlive,
  110. }).DialContext,
  111. MaxIdleConns: DefaultHttpMaxIdleConns,
  112. MaxIdleConnsPerHost: DefaultHttpMaxIdleConnsPerHost,
  113. IdleConnTimeout: DefaultHttpIdleConnTimeout,
  114. },
  115. Timeout: DefaultHttpTimeout, // 此处设置小于等于零的值,意为不超时
  116. }
  117. }
  118. // 设置https忽略本地证书校验
  119. func (r *RequestPromise) SetSkipTls() *RequestPromise {
  120. r.isSkipTls = true
  121. return r
  122. }
  123. // 设置http header
  124. func (r *RequestPromise) SetHeader(key string, value string) *RequestPromise {
  125. if len(strings.TrimSpace(key)) == 0 {
  126. return r
  127. }
  128. key = strings.TrimSpace(key)
  129. if nil == r.headers {
  130. r.headers = make(http.Header)
  131. }
  132. r.headers.Set(key, value)
  133. return r
  134. }
  135. // 设置http响应的编码,默认utf8
  136. func (r *RequestPromise) SetEncoding(encoding Charset) *RequestPromise {
  137. if encoding == UTF8 {
  138. return r
  139. }
  140. r.encoding = encoding
  141. return r
  142. }
  143. // 设置超时时间,从连接到接收到响应的总时间
  144. // 如果此处不设置则采用http client中设置的超时时间,默认http client超时时间30秒
  145. // 如果此处设置不等于零的值,则覆盖http client中设置的超时时间
  146. // 如果此处设置小于零的值,意为不超时
  147. func (r *RequestPromise) SetTimeout(timeout time.Duration) *RequestPromise {
  148. if timeout == 0 {
  149. return r
  150. }
  151. r.timeout = timeout
  152. return r
  153. }
  154. // 设置http或https代理,默认无代理
  155. func (r *RequestPromise) SetHttpProxy(proxyUri string) *RequestPromise {
  156. if len(strings.TrimSpace(proxyUri)) == 0 {
  157. return r
  158. }
  159. proxyUri = strings.TrimSpace(proxyUri)
  160. uri, err := (&url.URL{}).Parse(proxyUri)
  161. if nil != err {
  162. return r
  163. }
  164. r.proxy = http.ProxyURL(uri)
  165. return r
  166. }
  167. // 设置socket5代理,默认无代理
  168. func (r *RequestPromise) SetSocket5Proxy(proxyUri string) *RequestPromise {
  169. if len(strings.TrimSpace(proxyUri)) == 0 {
  170. return r
  171. }
  172. proxyUri = strings.TrimSpace(proxyUri)
  173. dialer, err := proxy.SOCKS5("tcp", proxyUri, nil, proxy.Direct)
  174. if nil != err {
  175. return r
  176. }
  177. r.dialContext = func(_ context.Context, network string, address string) (net.Conn, error) {
  178. return dialer.Dial(network, address)
  179. }
  180. return r
  181. }
  182. // 设置事先实例化好的http client,默认每次请求会新建一个http client
  183. func (r *RequestPromise) SetClient(client *http.Client) *RequestPromise {
  184. if nil == client {
  185. return r
  186. }
  187. r.client = client
  188. return r
  189. }
  190. // 发起请求并返回响应内容
  191. // FORM方式提交数据请设置Content-Type=application/x-www-form-urlencoded请求头,且io.Reader传url.Values.Encode得到的字符串的reader
  192. func (r *RequestPromise) Call(httpMethod string, targetUri string, data io.Reader) ([]byte, error) {
  193. targetUri = strings.TrimSpace(targetUri)
  194. if len(targetUri) == 0 {
  195. return nil, nil
  196. }
  197. // http request handle
  198. if len(strings.TrimSpace(httpMethod)) == 0 {
  199. httpMethod = http.MethodGet
  200. } else {
  201. httpMethod = strings.ToUpper(strings.TrimSpace(httpMethod))
  202. }
  203. req, err := http.NewRequest(httpMethod, targetUri, data)
  204. if err != nil {
  205. return nil, err
  206. }
  207. if nil != r.headers {
  208. req.Header = r.headers
  209. }
  210. r.initClient()
  211. // send http request & get http response
  212. resp, err := r.client.Do(req)
  213. if err != nil {
  214. return nil, err
  215. }
  216. return r.readResponseBody(resp)
  217. }
  218. func (r *RequestPromise) initClient() {
  219. // http client handle
  220. if nil == r.client { // create new http client instance
  221. r.client = &http.Client{Timeout: DefaultHttpTimeout} // default timeout
  222. }
  223. if r.timeout < 0 {
  224. r.timeout = DefaultHttpTimeout // default timeout
  225. }
  226. if r.timeout > 0 {
  227. r.client.Timeout = r.timeout
  228. }
  229. if r.isSkipTls {
  230. if nil == r.client.Transport {
  231. r.client.Transport = &http.Transport{}
  232. }
  233. transport := (r.client.Transport).(*http.Transport)
  234. transport.TLSClientConfig = &tls.Config{
  235. InsecureSkipVerify: true,
  236. //VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  237. // return nil
  238. //},
  239. }
  240. }
  241. if nil != r.proxy || nil != r.dialContext {
  242. if nil == r.client.Transport {
  243. r.client.Transport = &http.Transport{}
  244. }
  245. transport := (r.client.Transport).(*http.Transport)
  246. if nil != r.proxy {
  247. transport.Proxy = r.proxy
  248. }
  249. if nil != r.dialContext {
  250. transport.DialContext = r.dialContext
  251. }
  252. }
  253. }
  254. func (r *RequestPromise) readResponseBody(resp *http.Response) ([]byte, error) {
  255. defer func(body io.ReadCloser) {
  256. _ = body.Close()
  257. }(resp.Body)
  258. var reader io.ReadCloser
  259. switch resp.Header.Get("Content-Encoding") {
  260. case "gzip":
  261. reader, _ = gzip.NewReader(resp.Body)
  262. defer func(reader io.Closer) {
  263. _ = reader.Close()
  264. }(reader)
  265. case "deflate":
  266. reader = flate.NewReader(resp.Body)
  267. defer func(reader io.Closer) {
  268. _ = reader.Close()
  269. }(reader)
  270. case "zlib":
  271. reader, _ = zlib.NewReader(resp.Body)
  272. defer func(reader io.Closer) {
  273. _ = reader.Close()
  274. }(reader)
  275. default:
  276. reader = resp.Body
  277. }
  278. body, err := ioutil.ReadAll(reader)
  279. if err != nil {
  280. return nil, err
  281. }
  282. if r.encoding != "" {
  283. body = ConvertToEncodingBytes(body, r.encoding)
  284. }
  285. return body, nil
  286. }
  287. // 获取客户端IP地址
  288. func GetRemoteIP(req *http.Request) string {
  289. remoteAddr := req.RemoteAddr
  290. if ip := req.Header.Get("Remote_addr"); ip != "" {
  291. remoteAddr = ip
  292. } else {
  293. remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
  294. }
  295. if remoteAddr == "::1" {
  296. remoteAddr = "127.0.0.1"
  297. }
  298. return remoteAddr
  299. }