123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package utils
- import (
- "bytes"
- "crypto/tls"
- "fmt"
- "gd_auth_check/errors"
- "go.uber.org/zap"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- )
- 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
- }
|