client.go 1008 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
package httpclient

import (
	"io/ioutil"
	"net/http"
	"time"
)

var Default *http.Client

func init() {
	Default = NewClient()
}

func NewClient() *http.Client {
	// TODO: 相关参数可以考虑传参定义
	tr := http.DefaultTransport.(*http.Transport).Clone()
	tr.MaxIdleConnsPerHost = 32
	tr.MaxConnsPerHost = 32
	tr.MaxIdleConns = 64
	tr.IdleConnTimeout = time.Second * 30
	tr.DisableKeepAlives = false

	client := &http.Client{
		Transport: tr,
		Timeout:   time.Second * 5,
	}
	return client
}

func GetRemoteContent(url string) (string, error) {
	resp, err := Default.Get(url)

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	body, err2 := ioutil.ReadAll(resp.Body)

	if err2 != nil {
		return "", err
	}

	return string(body), nil
}

func GetRemoteBody(url string) ([]byte, error) {
	resp, err := Default.Get(url)

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		return nil, err
	}
	return body, nil
}