123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- package thirdparty
- import (
- "bytes"
- "crypto/tls"
- "gd_management/common.in/config"
- "gd_management/common.in/utils"
- "fmt"
- "go.uber.org/zap"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- )
- type HttpRequestWithHead struct {
- Url string
- Method string
- Head map[string]string
- TimeOut time.Duration
- Query map[string]string
- Body []byte
- }
- func (h HttpRequestWithHead) request() ([]byte, error) {
- request, err := http.NewRequest(h.Method, h.Url, bytes.NewReader(h.Body))
- if h.Method == http.MethodPost ||
- h.Method == http.MethodPut ||
- h.Method == http.MethodDelete {
- request.Header.Add("Content-Type", "application/json")
- }
- 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 {
- return nil, err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- if resp.Body == nil {
- return nil, fmt.Errorf("wrong status code: %d", resp.StatusCode)
- }
- contents, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("wrong status code: %d", resp.StatusCode)
- }
- return nil, fmt.Errorf("%s", contents)
- }
- contents, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- return contents, nil
- }
- func joinGetRequestArgs(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 HttpGetWithHead(path string, head map[string]string,
- query map[string]string) ([]byte, error) {
- if query != nil {
- path += joinGetRequestArgs(query)
- }
- h := HttpRequestWithHead{
- Url: path,
- Method: http.MethodGet,
- Head: head,
- TimeOut: 60 * time.Second,
- }
- return h.request()
- }
- func ZqyHttpGet(api string, data map[string]string) (result []byte, err error) {
- //fullApi := che300FullURL(api)
- defer func() {
- l.Info("ZqyHttpGet",
- zap.String("api", api),
- zap.String("request", utils.MarshalJsonString(data)),
- zap.String("response", utils.MarshalJsonString(result)))
- }()
- if data == nil {
- data = make(map[string]string)
- }
- data["key"] = config.Conf.ThirdPart.ZqyKey
- result, err = HttpGetWithHead(api, nil, data)
- if err != nil {
- return nil, err
- }
- return
- }
|