|
|
package util
import ( "bytes" "crypto/tls" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "time" )
type RequestMethod string type ContentType string type RequestHeader map[string][]string
const ( GET RequestMethod = "GET" POST RequestMethod = "POST" PUT RequestMethod = "PUT" DELETE RequestMethod = "DELETE" ) const ( ContentTypePlain ContentType = "text/plain;charset=utf-8" ContentTypeHtml ContentType = "text/html;charset=utf-8" ContentTypeXml ContentType = "text/xml;charset=utf-8" ContentTypeJson ContentType = "application/json;charset=utf-8" ContentTypeForm ContentType = "application/x-www-form-urlencoded;charset=utf-8" ContentTypeFile ContentType = "multipart/form-data;charset=utf-8" )
func Get(url string) ([]byte, error) { return Request(url, GET, ContentTypePlain, nil, nil) }
func Post(url string, contentType ContentType, v interface{}) ([]byte, error) { return Request(url, POST, contentType, nil, v) }
func Put(url string, contentType ContentType, v interface{}) ([]byte, error) { return Request(url, PUT, contentType, nil, v) }
func Del(url string) ([]byte, error) { return Request(url, DELETE, ContentTypePlain, nil, nil) }
func GetByHeader(url string, header RequestHeader) ([]byte, error) { return Request(url, GET, ContentTypePlain, header, nil) }
func PostByHeader(url string, contentType ContentType, header RequestHeader, v interface{}) ([]byte, error) { return Request(url, POST, contentType, header, v) }
func PutByHeader(url string, contentType ContentType, header RequestHeader, v interface{}) ([]byte, error) { return Request(url, PUT, contentType, header, v) }
func DelByHeader(url string, header RequestHeader) ([]byte, error) { return Request(url, DELETE, ContentTypePlain, header, nil) }
func GetJson(url string, v interface{}) ([]byte, error) { return Request(url, GET, ContentTypeJson, nil, v) }
func PostJson(url string, v interface{}) ([]byte, error) { return Request(url, POST, ContentTypeJson, nil, v) }
func PutJson(url string, v interface{}) ([]byte, error) { return Request(url, PUT, ContentTypeJson, nil, v) }
func DelJson(url string, v interface{}) ([]byte, error) { return Request(url, DELETE, ContentTypeJson, nil, v) }
func PostJsonByHeader(url string, header RequestHeader, v interface{}) ([]byte, error) { return Request(url, POST, ContentTypeJson, header, v) }
func PutJsonByHeader(url string, header RequestHeader, v interface{}) ([]byte, error) { return Request(url, PUT, ContentTypeJson, header, v) }
func Request(url string, method RequestMethod, contentType ContentType, header RequestHeader, v interface{}) ([]byte, error) { var body io.Reader var err error
//PrintInfo("response URL:")
//PrintInfo(url)
switch contentType { case ContentTypePlain: //return nil, fmt.Errorf("unsupported content-type:%s", contentType)
case ContentTypeHtml: return nil, fmt.Errorf("unsupported content-type:%s", contentType) case ContentTypeXml: return nil, fmt.Errorf("unsupported content-type:%s", contentType) case ContentTypeForm: return nil, fmt.Errorf("unsupported content-type:%s", contentType) case ContentTypeJson: body, err = toJson(v) case ContentTypeFile: return nil, fmt.Errorf("unsupported content-type:%s", contentType) default: return nil, fmt.Errorf("invalid content-type:%s", contentType) }
if err != nil { return nil, err }
tran := &http.Transport{ //TLSClientConfig: loadTlsConfig(),
}
client := &http.Client{Transport: tran, Timeout: time.Second * 180} req, err := http.NewRequest(string(method), url, body)
if err != nil { return nil, err }
req.Header.Set("Connection", "keep-alive")
if len(contentType) == 0 { contentType = ContentTypePlain } req.Header.Set("Content-Type", string(contentType))
if len(header) > 0 { for k, vs := range header { req.Header.Set(k, vs[0]) for i := 1; i < len(vs); i++ { req.Header.Add(k, vs[i]) } } }
rsp, err := client.Do(req)
if err != nil { closeBody(rsp) return nil, err }
return readRsp(rsp) }
func loadTlsConfig() *tls.Config { pemFile, err := FindFile("cert/2990195__241210.com.pem") if err != nil { panic(err) }
keyFile, err := FindFile("cert/2990195__241210.com.key") if err != nil { panic(err) }
PrintInfo(pemFile) PrintInfo(keyFile)
cert, err := tls.LoadX509KeyPair(pemFile, keyFile) if err != nil { panic(err) }
/*caFile, err := util.FindFile("cert/ca.pem") if err != nil { log.Fatalf("load CA cert err: %v", err) }
certPool := x509.NewCertPool() ca, err := ioutil.ReadFile(caFile) if err != nil { log.Fatalf("ioutil.ReadFile err: %v", err) }
if ok := certPool.AppendCertsFromPEM(ca); !ok { log.Fatalf("certPool.AppendCertsFromPEM err") }*/
tlsCfg := &tls.Config{ Certificates: []tls.Certificate{cert}, //ClientAuth: tls.RequireAndVerifyClientCert,
//ClientCAs: certPool,
InsecureSkipVerify: true, }
return tlsCfg }
func toJson(v interface{}) (*bytes.Buffer, error) { if v == nil { return nil, nil }
b, err := json.Marshal(v) if err != nil { return nil, err }
//PrintInfo("response data:")
//PrintJSON(v)
return bytes.NewBuffer(b), nil }
func readRsp(resp *http.Response) ([]byte, error) { defer closeBody(resp) return ioutil.ReadAll(resp.Body) }
func closeBody(resp *http.Response) { if resp != nil && resp.Body != nil { err := resp.Body.Close() if err != nil { PrintErr(err) } } }
|