本文整理汇总了Golang中net/http.Client.Timeout方法的典型用法代码示例。如果您正苦于以下问题:Golang Client.Timeout方法的具体用法?Golang Client.Timeout怎么用?Golang Client.Timeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Client
的用法示例。
在下文中一共展示了Client.Timeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Curl
//provides a httpResponse for a GET,DELETE,POST or PUT. Can support json data, use "json" as a key on the parmeter
func Curl(p RequestParms) (*http.Response, error) {
var client http.Client
var req *http.Request
var resp *http.Response
var err error
client.Timeout = p.Timeout
if client.Timeout == 0 {
client.Timeout = time.Second * DEFAULT_TIMEOUT
}
if p.Method == HTTP_GET || p.Method == HTTP_DELETE {
url := buildGetUrl(p.Params, p.Endpoint)
req, _ = http.NewRequest(p.Method, url, nil)
p.populateHeaders(req)
resp, err = client.Do(req)
}
if p.Method == HTTP_POST || p.Method == HTTP_PUT {
url := p.Endpoint
data := formValues(p.Params)
req, err = http.NewRequest(p.Method, url, bytes.NewBufferString(data.Encode()))
if err != nil {
log.Println(err)
}
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
if p.Headers == nil {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
} else {
p.populateHeaders(req)
}
resp, err = client.Do(req)
}
if p.Method == HTTP_JSONPOST {
url := p.Endpoint
data := p.Params["json"]
req, err = http.NewRequest("POST", url, bytes.NewBufferString(data))
if err != nil {
log.Println(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(data)))
p.populateHeaders(req)
resp, err = client.Do(req)
}
return resp, err
}
示例2: startupHealthcheck
// startupHealthcheck is used at startup to check if the server is available
// at all.
func (c *Client) startupHealthcheck(timeout time.Duration) error {
c.mu.Lock()
urls := c.urls
c.mu.Unlock()
// If we don't get a connection after "timeout", we bail.
start := time.Now()
for {
// Make a copy of the HTTP client provided via options to respect
// settings like Basic Auth or a user-specified http.Transport.
cl := new(http.Client)
*cl = *c.c
cl.Timeout = timeout
for _, url := range urls {
res, err := cl.Head(url)
if err == nil && res != nil && res.StatusCode >= 200 && res.StatusCode < 300 {
return nil
}
}
time.Sleep(1 * time.Second)
if time.Now().Sub(start) > timeout {
break
}
}
return ErrNoClient
}
示例3: main
func main() {
runtime.GOMAXPROCS(4)
scanner := bufio.NewScanner(os.Stdin)
hosts := make(chan string)
client := http.Client{}
client.Timeout = 2 * time.Second
seen := make(map[string]struct{})
wg := sync.WaitGroup{}
go func() {
for host := range hosts {
fmt.Println(host)
}
}()
for scanner.Scan() {
targetUrl := scanner.Text()
if _, there := seen[targetUrl]; !there {
wg.Add(1)
go func() {
defer wg.Done()
resolve(targetUrl, client, hosts)
}()
seen[targetUrl] = struct{}{}
}
}
wg.Wait()
}
示例4: GetWANIP
// Also you can use;
// bot.whatismyipaddress.com
// https://api.ipify.org
func GetWANIP() (string, error) {
var hc http.Client
var reader io.Reader
req, err := http.NewRequest("GET", "http://icanhazip.com", reader)
if err != nil {
return "", err
}
hc.Timeout = time.Duration(4) * time.Second
resp, err := hc.Do(req)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
defer resp.Body.Close()
ipstr := strings.TrimSpace(string(body))
if !isValidIPv4(ipstr) {
return "", errors.New("Invalid IPv4 address: " + ipstr)
}
return ipstr, err
}
示例5: UnversionedRESTClientFor
// UnversionedRESTClientFor is the same as RESTClientFor, except that it allows
// the config.Version to be empty.
func UnversionedRESTClientFor(config *Config) (*RESTClient, error) {
if config.NegotiatedSerializer == nil {
return nil, fmt.Errorf("NeogitatedSerializer is required when initializing a RESTClient")
}
baseURL, versionedAPIPath, err := defaultServerUrlFor(config)
if err != nil {
return nil, err
}
transport, err := TransportFor(config)
if err != nil {
return nil, err
}
var httpClient *http.Client
if transport != http.DefaultTransport {
httpClient = &http.Client{Transport: transport}
if config.Timeout > 0 {
httpClient.Timeout = config.Timeout
}
}
versionConfig := config.ContentConfig
if versionConfig.GroupVersion == nil {
v := metav1.SchemeGroupVersion
versionConfig.GroupVersion = &v
}
return NewRESTClient(baseURL, versionedAPIPath, versionConfig, config.QPS, config.Burst, config.RateLimiter, httpClient)
}
示例6: get
func get(url_ string, header http.Header, timeout time.Duration) (*http.Response, error) {
for i := 0; i < 10; i += 1 {
client := http.Client{CheckRedirect: CheckRedirect}
client.Timeout = timeout
req, err := http.NewRequest("GET", url_, nil)
if err != nil {
return nil, err
}
// log.Printf("url: %v\n\n", req.URL)
req.Header = header
resp, err := client.Do(req)
// log.Print(resp.Header)
if err != nil {
switch err.(*url.Error).Err.(type) {
case RedirectError:
tmp, err := resp.Location()
if err != nil {
return nil, err
}
url_ = tmp.String()
continue
default:
return nil, err
}
} else {
return resp, err
}
}
return nil, fmt.Errorf("unknow error")
}
示例7: submitRequest
// submitRequest uses a given client and submits the specified request.
func (c *SecureContext) submitRequest(rw http.ResponseWriter, req *http.Request, url string, client *http.Client, responseHandler ResponseHandler) {
// Prevents lingering goroutines from living forever.
// http://stackoverflow.com/questions/16895294/how-to-set-timeout-for-http-get-requests-in-golang/25344458#25344458
client.Timeout = 5 * time.Second
// In case the body is not of io.Closer.
if req.Body != nil {
defer req.Body.Close()
}
req.Close = true
// Make a new request.
request, _ := http.NewRequest(req.Method, url, req.Body)
// In case the body is not of io.Closer.
if request.Body != nil {
defer request.Body.Close()
}
request.Close = true
// Send the request.
res, err := client.Do(request)
if res != nil {
defer res.Body.Close()
}
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "unknown error. try again")
return
}
// Should return the same status.
rw.WriteHeader(res.StatusCode)
responseHandler(&rw, res)
}
示例8: testHttp
// Test a HTTP call.
func testHttp(test HttpHealthCheckAttributes, handler ResponseHandler) {
client := http.Client{}
client.Timeout = test.Timeout
request := &http.Request{
Method: "GET",
URL: test.Url,
Close: true,
}
time_start := time.Now()
res, err := client.Do(request)
total_time := time.Since(time_start)
if err != nil {
handler.Failed(map[string]interface{}{
"error": fmt.Errorf("HTTP call failed with: %s", err),
})
return
}
res.Body.Close()
if res.StatusCode == http.StatusOK {
handler.Passed(map[string]interface{}{
"latency": total_time,
})
return
}
handler.Failed(map[string]interface{}{
"error": fmt.Errorf("Invalid response code: %s", res.StatusCode),
})
}
示例9: NewSender
// NewSender creates a new Sender and sets a timeout on the http.Client
func NewSender(apiKey string, retryCount int, timeout time.Duration) *Client {
httpClient := new(http.Client)
httpClient.Timeout = timeout
return &Client{
APIKey: apiKey,
RetryCount: retryCount,
HTTPClient: httpClient,
}
}
示例10: exec
func (c Client) exec(verb, url string, headers map[string]string, body io.Reader) (*storageResponse, error) {
authHeader, err := c.getAuthorizationHeader(verb, url, headers)
if err != nil {
return nil, err
}
headers["Authorization"] = authHeader
if err != nil {
return nil, err
}
req, err := http.NewRequest(verb, url, body)
for k, v := range headers {
req.Header.Add(k, v)
}
httpClient := http.Client{}
httpClient.Timeout = c.Timeout
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
statusCode := resp.StatusCode
if statusCode >= 400 && statusCode <= 505 {
var respBody []byte
respBody, err = readResponseBody(resp)
if err != nil {
return nil, err
}
if len(respBody) == 0 {
// no error in response body
err = fmt.Errorf("storage: service returned without a response body (%s)", resp.Status)
} else {
// response contains storage service error object, unmarshal
storageErr, errIn := serviceErrFromXML(respBody, resp.StatusCode, resp.Header.Get("x-ms-request-id"))
if err != nil { // error unmarshaling the error response
err = errIn
}
err = storageErr
}
return &storageResponse{
statusCode: resp.StatusCode,
headers: resp.Header,
body: ioutil.NopCloser(bytes.NewReader(respBody)), /* restore the body */
}, err
}
return &storageResponse{
statusCode: resp.StatusCode,
headers: resp.Header,
body: resp.Body}, nil
}
示例11: New
// Creates a new Trade based on the given cookies `sessionid`, `steamLogin`, `steamLoginSecure` and the trade partner's Steam ID.
func New(sessionId, steamLogin, steamLoginSecure string, other steamid.SteamId) *Trade {
client := new(http.Client)
client.Timeout = 10 * time.Second
t := &Trade{
client: client,
other: other,
sessionId: sessionId,
baseUrl: fmt.Sprintf(tradeUrl, other),
Version: 1,
}
community.SetCookies(t.client, sessionId, steamLogin, steamLoginSecure)
return t
}
示例12: GetImage
func (br *Bracelet) GetImage(str string) (string, error) {
client := http.Client{}
client.Timeout = time.Second * 10
v := url.Values{}
v.Set("str", str)
resp, err := client.PostForm("http://"+br.Address.ImConv+"/", v)
if err != nil {
return "", err
}
defer resp.Body.Close()
buf := &bytes.Buffer{}
buf.ReadFrom(resp.Body)
return hex.EncodeToString(buf.Bytes()), nil
}
示例13: LookupIPWithClient
// LookupIPWithClient looks up the given IP using a geolocation service and returns a
// City struct. If an httpClient was provided, it uses that, otherwise it uses
// a default http.Client.
func LookupIPWithClient(ipAddr string, httpClient *http.Client) (*City, string, error) {
if httpClient == nil {
log.Trace("Using default http.Client")
httpClient = defaultHttpClient
}
httpClient.Timeout = geoLookupTimeout
var err error
var req *http.Request
var resp *http.Response
lookupURL := fmt.Sprintf(geoServeEndpoint, ipAddr)
if req, err = http.NewRequest("GET", lookupURL, nil); err != nil {
return nil, "", fmt.Errorf("Could not create request: %q", err)
}
if resp, err = httpClient.Do(req); err != nil {
return nil, "", fmt.Errorf("Could not get response from server: %q", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Debugf("Unable to close reponse body: %v", err)
}
}()
if resp.StatusCode != http.StatusOK {
body := "body unreadable"
b, err := ioutil.ReadAll(resp.Body)
if err == nil {
body = string(b)
}
return nil, "", fmt.Errorf("Unexpected response status %d: %v", resp.StatusCode, body)
}
ip := resp.Header.Get("X-Reflected-Ip")
decoder := json.NewDecoder(resp.Body)
city := &City{}
if err = decoder.Decode(city); err != nil {
return nil, ip, err
}
return city, ip, nil
}
示例14: do
func (self *Client) do(req *http.Request) (*http.Response, error) {
client := new(http.Client)
// Adding cookie jar
if self.CookieJar != nil {
client.Jar = self.CookieJar
}
// Copying headers
for k := range self.Header {
req.Header.Set(k, self.Header.Get(k))
}
if req.Body == nil {
req.Header.Del("Content-Type")
req.Header.Del("Content-Length")
}
client.Timeout = self.Timeout
res, err := client.Do(req)
if debugLevelEnabled(debugLevelVerbose) {
log.Printf("Fetching %v\n", req.URL.String())
log.Printf("> %s %s", req.Method, req.Proto)
for k := range req.Header {
for kk := range req.Header[k] {
log.Printf("> %s: %s", k, req.Header[k][kk])
}
}
log.Printf("< %s %s", res.Proto, res.Status)
for k := range res.Header {
for kk := range res.Header[k] {
log.Printf("< %s: %s", k, res.Header[k][kk])
}
}
log.Printf("\n")
}
return res, err
}
示例15: Do
// Do creates an http.Client and runs Do
func (doer *HTTPDoer) Do(timeout time.Duration) error {
client := new(http.Client)
client.Timeout = timeout
response, err := client.Do(doer.request)
doer.response = response
if err != nil {
return err
}
defer doer.response.Body.Close()
doer.responseBytes, err = ioutil.ReadAll(doer.response.Body)
if err != nil {
return err
}
return nil
}