12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package thirdparty
- import (
- "bytes"
- "crypto/tls"
- "fmt"
- "gd_service/errors"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- "go.uber.org/zap"
- )
- type HttpRequestWithHeadCommon struct {
- Url string
- Method string
- Head map[string]string
- TimeOut time.Duration
- Query map[string]string
- Body []byte
- }
- func joinGetRequestArgsCommon(data map[string]string) string {
- var path string
- if data != nil {
- path += "?"
- for k, v := range data {
- path += k + "=" + v + "&"
- }
- path = strings.TrimRight(path, "&")
- return path
- }
- return path
- }
- func (h HttpRequestWithHeadCommon) Request() ([]byte, error) {
- if len(h.Query) > 0 {
- h.Url = h.Url + joinGetRequestArgsCommon(h.Query)
- }
- request, err := http.NewRequest(h.Method, h.Url, bytes.NewReader(h.Body))
- for k, v := range h.Head {
- request.Header.Add(k, v)
- }
- //跳过证书验证
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }
- client := http.Client{
- Transport: tr,
- Timeout: h.TimeOut,
- }
- resp, err := client.Do(request)
- if err != nil {
- l.Error("thirdpary",
- zap.String("call", "http request"),
- zap.String("url", h.Url),
- zap.String("error", err.Error()))
- return nil, errors.VendorError
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- l.Error("thirdpary",
- zap.String("call", "http request"),
- zap.String("url", h.Url),
- zap.String("error", fmt.Sprintf("http wrong status:%d", resp.StatusCode)))
- return nil, errors.VendorError
- }
- contents, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- l.Error("thirdpary",
- zap.String("call", "http request"),
- zap.String("url", h.Url),
- zap.String("error", err.Error()))
- return nil, errors.VendorError
- }
- return contents, nil
- }
|