当前位置: 首页>>代码示例>>Golang>>正文


Golang Client.Timeout方法代码示例

本文整理汇总了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
}
开发者ID:vtuson,项目名称:vtputils,代码行数:49,代码来源:curl.go

示例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
}
开发者ID:adamweiner,项目名称:elastic.v2-gzip,代码行数:29,代码来源:client.go

示例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()
}
开发者ID:ZacharyForman,项目名称:small-projects,代码行数:26,代码来源:url_resolver.go

示例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
}
开发者ID:c1982,项目名称:dynogo,代码行数:36,代码来源:helper.go

示例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)
}
开发者ID:alex-mohr,项目名称:kubernetes,代码行数:33,代码来源:config.go

示例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")
}
开发者ID:Geoion,项目名称:mcurl,代码行数:30,代码来源:utils.go

示例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)
}
开发者ID:ArthurHlt,项目名称:cg-deck,代码行数:31,代码来源:secure.go

示例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),
	})
}
开发者ID:bweston92,项目名称:vigour,代码行数:33,代码来源:http.go

示例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,
	}
}
开发者ID:Aorioli,项目名称:gcm,代码行数:10,代码来源:sender.go

示例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
}
开发者ID:StorReduce,项目名称:azure-sdk-for-go,代码行数:55,代码来源:client.go

示例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
}
开发者ID:zhuharev,项目名称:go-steam,代码行数:15,代码来源:trade.go

示例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
}
开发者ID:seka17,项目名称:bracelet,代码行数:17,代码来源:image.go

示例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
}
开发者ID:kidaa,项目名称:lantern,代码行数:49,代码来源:geolookup.go

示例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
}
开发者ID:khaf,项目名称:rest,代码行数:45,代码来源:main.go

示例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
}
开发者ID:the-control-group,项目名称:go-whitepages,代码行数:19,代码来源:http.go


注:本文中的net/http.Client.Timeout方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。