package rpc import ( "git.hilo.cn/hilo-common/domain" "io/ioutil" "net" "net/http" "net/url" "strings" ) var httpTransport = &http.Transport{ MaxIdleConnsPerHost: defaultMaxIdleConnsPerHost, MaxIdleConns: defaultMaxIdleConns, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: defaultDialTimeout, KeepAlive: defaultKeepAliveTimeout, }).DialContext, IdleConnTimeout: defaultIdleConnTimeout, TLSHandshakeTimeout: defaultTLSHandshakeTimeout, ExpectContinueTimeout: defaultExpectContinueTimeout, } // 执行http get请求 // param: header + postForm // return: resp body,err func HttpGet(model *domain.Model, _url string, header map[string]string, query map[string][]string) ([]byte, error) { var err error defer func() { if err != nil { model.Log.Errorf("HttpPut err:%v", err) } }() if len(query) > 0 { q := url.Values{} for k, v := range query { for _, v2 := range v { q.Add(k, v2) } } _url += "?" + q.Encode() } req, err := http.NewRequest("GET", _url, nil) if err != nil { return nil, err } for k, v := range header { req.Header.Add(k, v) } resp, err := httpTransport.RoundTrip(req) if err != nil { return nil, err } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp != nil { err = resp.Body.Close() } return body, err } // 执行http post请求 // 默认: Content-Type":"application/x-www-form-urlencoded" // param: header + postForm // return: resp body,err func HttpPostForm(model *domain.Model, _url string, header, form map[string]string) ([]byte, error) { return httpForm(model, "POST", _url, header, form) } // 执行http put请求 // 默认: Content-Type":"application/x-www-form-urlencoded" // param: header + postForm // return: resp body,err func HttpPutForm(model *domain.Model, _url string, header map[string]string, form map[string]string) ([]byte, error) { return httpForm(model, "PUT", _url, header, form) } // 默认: Content-Type":"application/x-www-form-urlencoded" // param: header + postForm // return: resp body,err func httpForm(model *domain.Model, method, _url string, header map[string]string, form map[string]string) ([]byte, error) { var err error defer func() { if err != nil { model.Log.Errorf("HttpPut err:%v", err) } }() postForm := url.Values{} for k, v := range form { postForm.Set(k, v) } payload := strings.NewReader(postForm.Encode()) req, err := http.NewRequest(method, _url, payload) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") if err != nil { return nil, err } for k, v := range header { req.Header.Add(k, v) } resp, err := httpTransport.RoundTrip(req) if err != nil { return nil, err } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp != nil { err = resp.Body.Close() } return body, err }