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


Golang http.Client类代码示例

本文整理汇总了Golang中net/http.Client的典型用法代码示例。如果您正苦于以下问题:Golang Client类的具体用法?Golang Client怎么用?Golang Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: getQuote

func getQuote(symbol string) float64 {
	// set http timeout
	client := http.Client{Timeout: timeout}

	url := fmt.Sprintf("http://finance.yahoo.com/webservice/v1/symbols/%s/quote?format=json", symbol)
	res, err := client.Get(url)
	if err != nil {
		fmt.Errorf("Stocks cannot access the yahoo finance API: %v", err)
	}
	defer res.Body.Close()

	content, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf("Stocks cannot read json body: %v", err)
	}

	var stock Stock

	err = json.Unmarshal(content, &stock)
	if err != nil {
		fmt.Errorf("Stocks cannot parse the json data: %v", err)
	}

	price, err := strconv.ParseFloat(stock.List.Resources[0].Resource.Fields.Price, 64)
	if err != nil {
		fmt.Errorf("Stock price: %v", err)
	}

	return price
}
开发者ID:minervaDutta,项目名称:CMPE273-Assignment1,代码行数:30,代码来源:yahooFinanceServer.go

示例2: authenticateWithBackend

func authenticateWithBackend(req *http.Request) (bool, error) {
	auth, authExists := req.Header["Authorization"]
	if authExists && isCached(auth[0]) {
		return true, nil
	}

	var r *http.Request
	var err error
	var resp *http.Response

	r, err = http.NewRequest("GET", planio_url, nil)
	if err != nil {
		return false, err
	}
	r.Header["Authorization"] = auth

	client := http.Client{}
	resp, err = client.Do(r)
	if err != nil {
		return false, err
	}

	resp.Body.Close()
	if resp.StatusCode == 200 {
		if authExists {
			addToCache(auth[0])
		}
		return true, nil
	}
	return false, nil
}
开发者ID:Recras,项目名称:jenkins-authentication-proxy,代码行数:31,代码来源:jenkins-authentication-proxy.go

示例3: getAppID

func getAppID(client *http.Client, url string) (string, error) {
	// Generate a pseudo-random token for handshaking.
	token := strconv.Itoa(rand.New(rand.NewSource(time.Now().UnixNano())).Int())

	resp, err := client.Get(fmt.Sprintf("%s?rtok=%s", url, token))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("bad response %d; body: %q", resp.StatusCode, body)
	}
	if err != nil {
		return "", fmt.Errorf("failed reading response: %v", err)
	}

	// Check the token is present in response.
	if !bytes.Contains(body, []byte(token)) {
		return "", fmt.Errorf("token not found: want %q; body %q", token, body)
	}

	match := appIDRE.FindSubmatch(body)
	if match == nil {
		return "", fmt.Errorf("app ID not found: body %q", body)
	}

	return string(match[1]), nil
}
开发者ID:odeke-em,项目名称:appengine-go,代码行数:30,代码来源:client.go

示例4: IsLeaderAlive

func IsLeaderAlive(currentLeader string) {

	if retryCount > 0 {
		fmt.Println("Trying......", retryCount)
		transport := http.Transport{
			Dial: dialTimeout,
		}

		client := http.Client{
			Transport: &transport,
		}

		url := fmt.Sprintf("http://localhost:%s/isalive", currentLeader)
		res, err := client.Get(url)

		if err != nil {

			time.Sleep(5000 * time.Millisecond)
			retryCount--
			IsLeaderAlive(currentLeader)
		}

		fmt.Println("Response Status:", res.StatusCode)
		if res.StatusCode == 200 {
			time.Sleep(5000 * time.Millisecond)
			IsLeaderAlive(currentLeader)
		}
	} else {
		resp, _ := http.Get("http://localhost:9999/flushall")
		resp.Body.Close()
		initiateElection()
	}
}
开发者ID:DhruvKalaria,项目名称:RAFT-Implementation,代码行数:33,代码来源:n2.go

示例5: postJSON

func postJSON(jsonMessage []byte, url string) (*http.Response, error) {
	timeout := time.Duration(5 * time.Second)
	client := http.Client{
		Timeout: timeout,
	}
	return client.Post(url, contentTypeJSON, bytes.NewBuffer(jsonMessage))
}
开发者ID:tamsky,项目名称:alertmanager,代码行数:7,代码来源:notifier.go

示例6: TestSslSupport

func (self *ServerSuite) TestSslSupport(c *C) {
	data := `
  [{
    "points": [
        ["val1", 2]
    ],
    "name": "test_sll",
    "columns": ["val_1", "val_2"]
  }]`
	self.serverProcesses[0].Post("/db/test_rep/series?u=paul&p=pass", data, c)

	encodedQuery := url.QueryEscape("select * from test_sll")
	fullUrl := fmt.Sprintf("https://localhost:60503/db/test_rep/series?u=paul&p=pass&q=%s", encodedQuery)
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := http.Client{
		Transport: transport,
	}
	resp, err := client.Get(fullUrl)
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	body, err := ioutil.ReadAll(resp.Body)
	c.Assert(err, IsNil)
	var js []*common.SerializedSeries
	err = json.Unmarshal(body, &js)
	c.Assert(err, IsNil)
	collection := ResultsToSeriesCollection(js)
	series := collection.GetSeries("test_sll", c)
	c.Assert(len(series.Points) > 0, Equals, true)
}
开发者ID:rramos,项目名称:influxdb,代码行数:32,代码来源:server_test.go

示例7: TestWatchHTTPAccept

func TestWatchHTTPAccept(t *testing.T) {
	simpleStorage := &SimpleRESTStorage{}
	handler := handle(map[string]rest.Storage{"simples": simpleStorage})
	server := httptest.NewServer(handler)
	defer server.Close()
	client := http.Client{}

	dest, _ := url.Parse(server.URL)
	dest.Path = "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simples"
	dest.RawQuery = ""

	request, err := http.NewRequest("GET", dest.String(), nil)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	request.Header.Set("Accept", "application/XYZ")
	response, err := client.Do(request)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	// TODO: once this is fixed, this test will change
	if response.StatusCode != http.StatusNotAcceptable {
		t.Errorf("Unexpected response %#v", response)
	}
}
开发者ID:ncdc,项目名称:kubernetes,代码行数:27,代码来源:watch_test.go

示例8: submitVded

func submitVded(host string, metricName string, value int64) (e error) {
	if *vdedServer == "" {
		return errors.New("No VDED server, cannot continue")
	}

	url := fmt.Sprintf("http://%s:48333/vector?host=%s&vector=delta_%s&value=%d&ts=%d&submit_metric=1", *vdedServer, host, metricName, value, time.Now().Unix())
	log.Debug("VDED: " + url)

	c := http.Client{
		Transport: &http.Transport{
			Dial: timeoutDialer(time.Duration(5) * time.Second),
		},
	}

	resp, err := c.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	log.Debug("VDED returned: " + string(body))

	return
}
开发者ID:jbuchbinder,项目名称:ganglia-activemq,代码行数:27,代码来源:main.go

示例9: asyncHttpGets

func asyncHttpGets(urls []string) []*HttpResponse {
	ch := make(chan *HttpResponse)
	responses := []*HttpResponse{}
	client := http.Client{}
	for _, url := range urls {
		go func(url string) {
			fmt.Printf("Fetching %s \n", url)
			resp, err := client.Get(url)
			ch <- &HttpResponse{url, resp, err}
			if err != nil && resp != nil && resp.StatusCode == http.StatusOK {
				resp.Body.Close()
			}
		}(url)
	}

	for {
		select {
		case r := <-ch:
			fmt.Printf("%s was fetched\n", r.url)
			if r.err != nil {
				fmt.Println("with an error", r.err)
			}
			responses = append(responses, r)
			if len(responses) == len(urls) {
				return responses
			}
		case <-time.After(50 * time.Millisecond):
			fmt.Printf(".")
		}
	}
	return responses
}
开发者ID:dana,项目名称:golang-misc,代码行数:32,代码来源:server.go

示例10: v1CompatBroadcast

func v1CompatBroadcast(
	ctx *grader.Context,
	client *http.Client,
	message *broadcaster.Message,
) error {
	marshaled, err := json.Marshal(message)
	if err != nil {
		return err
	}

	resp, err := client.Post(
		"https://localhost:32672/broadcast/",
		"text/json",
		bytes.NewReader(marshaled),
	)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf(
			"Request to broadcast failed with error code %d",
			resp.StatusCode,
		)
	}
	return nil
}
开发者ID:lhchavez,项目名称:quark,代码行数:26,代码来源:v1compat_handler.go

示例11: ExpireTokens

func (g *Adaptor) ExpireTokens(userID int) error {
	request := ExpireTokenRequest{Action: "all"}

	gandalfUrl := fmt.Sprintf("http://%s:%d/expire/%d", g.GandalfHost, g.GandalfPort, userID)
	client := http.Client{}

	marshalledReq, err := json.Marshal(request)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", gandalfUrl, bytes.NewBuffer(marshalledReq))
	if err != nil {
		return err
	}

	resp, err := client.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return errors.New("failed to expire tokens")
	}

	return nil
}
开发者ID:john-cai,项目名称:tools,代码行数:29,代码来源:gandalf_adapter.go

示例12: GetCookieConfig

// GetCookieConfig returns settings needed to set a Crowd SSO cookie.
func (c *Crowd) GetCookieConfig() (CookieConfig, error) {
	cc := CookieConfig{}

	client := http.Client{Jar: c.cookies}
	req, err := http.NewRequest("GET", c.url+"rest/usermanagement/1/config/cookie", nil)
	if err != nil {
		return cc, err
	}
	req.SetBasicAuth(c.user, c.passwd)
	req.Header.Set("Accept", "application/xml")
	req.Header.Set("Content-Type", "application/xml")
	resp, err := client.Do(req)
	if err != nil {
		return cc, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return cc, fmt.Errorf("request failed: %s\n", resp.Status)
	}

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

	err = xml.Unmarshal(body, &cc)
	if err != nil {
		return cc, err
	}

	return cc, nil
}
开发者ID:Netwurx,项目名称:kayako-crowd-loginshare,代码行数:33,代码来源:cookie.go

示例13: getLeaderStatus

func getLeaderStatus(tr *http.Transport, endpoints []string) (string, raftStatus, error) {
	// TODO: use new etcd client
	httpclient := http.Client{
		Transport: tr,
	}

	for _, ep := range endpoints {
		resp, err := httpclient.Get(ep + "/debug/vars")
		if err != nil {
			continue
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			continue
		}

		vs := &vars{}
		d := json.NewDecoder(resp.Body)
		err = d.Decode(vs)
		if err != nil {
			continue
		}
		if vs.RaftStatus.Lead != vs.RaftStatus.ID {
			continue
		}
		return ep, vs.RaftStatus, nil
	}
	return "", raftStatus{}, errors.New("no leader")
}
开发者ID:Nano1994,项目名称:etcd,代码行数:29,代码来源:cluster_health.go

示例14: PublicKey

// PublicKey requests a shadowfax server's public key. An error is returned
// if the server URL is not https.
func PublicKey(serverURL string, client *http.Client) (*sf.PublicKey, error) {
	u, err := url.Parse(serverURL)
	if err != nil {
		return nil, errgo.Mask(err, errgo.Any)
	}
	if u.Scheme != "https" {
		return nil, errgo.Newf("public key must be requested with https")
	}
	if client == nil {
		client = http.DefaultClient
	}
	req, err := http.NewRequest("GET", serverURL+"/publickey", nil)
	if err != nil {
		return nil, errgo.Mask(err)
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, errgo.Mask(err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	var publicKeyResp wire.PublicKeyResponse
	err = dec.Decode(&publicKeyResp)
	if err != nil {
		return nil, errgo.Mask(err)
	}

	publicKey, err := sf.DecodePublicKey(publicKeyResp.PublicKey)
	if err != nil {
		return nil, errgo.Mask(err)
	}
	return publicKey, nil
}
开发者ID:cmars,项目名称:shadowfax,代码行数:37,代码来源:client.go

示例15: makeRequest

// makeRequest is a wrapper function used for making DNS API requests
func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) {
	url := c.cloudDNSEndpoint + uri
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}

	req.Header.Set("X-Auth-Token", c.token)
	req.Header.Set("Content-Type", "application/json")

	client := http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("Error querying DNS API: %v", err)
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
		return nil, fmt.Errorf("Request failed for %s %s. Response code: %d", method, url, resp.StatusCode)
	}

	var r json.RawMessage
	err = json.NewDecoder(resp.Body).Decode(&r)
	if err != nil {
		return nil, fmt.Errorf("JSON decode failed for %s %s. Response code: %d", method, url, resp.StatusCode)
	}

	return r, nil
}
开发者ID:Rudloff,项目名称:platform,代码行数:31,代码来源:rackspace.go


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