// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package thirdparty import ( "bytes" "crypto/tls" "fmt" "io/ioutil" "net/http" "property-thirdparty/errors" "strings" "time" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" ) type HttpRequestWithHead struct { Url string Method string Head map[string]string TimeOut time.Duration Query map[string]string Body []byte } 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 (h HttpRequestWithHead) Request() ([]byte, error) { if len(h.Query) > 0 { h.Url = h.Url + joinGetRequestArgs(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 { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { logger.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 { logger.Error("thirdpary", zap.String("call", "http request"), zap.String("url", h.Url), zap.String("error", err.Error())) return nil, errors.VendorError } return contents, nil }