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


Golang Client.Get方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: main

func main() {
	baseURL := "http://axe-level-1.herokuapp.com/lv3"
	firstPage := true

	jar, err := cookiejar.New(nil)
	if err != nil {
		fmt.Println("cannot create cookiejar!?")
		return
	}
	client := http.Client{Jar: jar}

	towns := make([]*AreaLeader, 0, 1024)
	for {
		var resp *http.Response
		if resp, err = client.Get(baseURL); err != nil {
			fmt.Println("cannot get page!?")
			return
		}
		if firstPage {
			firstPage = false
			baseURL = baseURL + "?page=next"
		}
		newTowns, hasNext := parsePage(resp)

		towns = append(towns, newTowns...)
		if !hasNext {
			break
		}
	}
	//fmt.Println("len(towns)", len(towns))

	if err := json.NewEncoder(os.Stdout).Encode(towns); err != nil {
		fmt.Println(err)
	}
}
开发者ID:redeyes2015,项目名称:junkcodes,代码行数:35,代码来源:3.go

示例6: GetVersions

func (clair ClairAPI) GetVersions() (versions GetVersionsAnswer, err error) {
	var client *http.Client
	url := clair.Address + ":" + strconv.Itoa(clair.Port) + "/v1/versions"
	if clair.HttpsEnable {
		url = "https://" + url
		client = tlsClient
	} else {
		url = "http://" + url
		client = httpClient
	}

	response, err := client.Get(url)
	if err != nil {
		log.Println("Send request failed request: ", err)
		return
	}

	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)

	// if OK  - returned "200 OK"
	if response.StatusCode != 200 {
		log.Println("Error - response not ok - ", response.Status, " with message: ", string(body))
		return versions, errors.New(string(body))
	}

	err = json.Unmarshal(body, &versions)
	if err != nil {
		log.Println("Cannot parse answer from clair to json: ", err)
		return
	}
	return
}
开发者ID:jlamcanopy,项目名称:clair,代码行数:33,代码来源:main.go

示例7: runQuery

func runQuery(t *testing.T, expected int, shouldErr bool, wg *sync.WaitGroup) {
	wg.Add(1)
	defer wg.Done()
	client := http.Client{}
	r, err := client.Get("http://localhost:3000")
	if shouldErr && err == nil {
		t.Fatal("Expected an error but none was encountered.")
	} else if shouldErr && err != nil {
		if err.(*url.Error).Err == io.EOF {
			return
		}
		errno := err.(*url.Error).Err.(*net.OpError).Err.(syscall.Errno)
		if errno == syscall.ECONNREFUSED {
			return
		} else if err != nil {
			t.Fatal("Error on Get:", err)
		}
	}

	if r != nil && r.StatusCode != expected {
		t.Fatalf("Incorrect status code on response. Expected %d. Got %d", expected, r.StatusCode)
	} else if r == nil {
		t.Fatal("No response when a response was expected.")
	}
}
开发者ID:gotstago,项目名称:go-tarabish,代码行数:25,代码来源:graceful_test.go

示例8: LongPollDelta

// LongPollDelta waits for a notification to happen.
func (db *Dropbox) LongPollDelta(cursor string, timeout int) (*DeltaPoll, error) {
	var rv DeltaPoll
	var params *url.Values
	var body []byte
	var rawurl string
	var response *http.Response
	var err error
	var client http.Client

	params = &url.Values{}
	if timeout != 0 {
		if timeout < PollMinTimeout || timeout > PollMaxTimeout {
			return nil, fmt.Errorf("timeout out of range [%d; %d]", PollMinTimeout, PollMaxTimeout)
		}
		params.Set("timeout", strconv.FormatInt(int64(timeout), 10))
	}
	params.Set("cursor", cursor)
	rawurl = fmt.Sprintf("%s/longpoll_delta?%s", db.APINotifyURL, params.Encode())
	if response, err = client.Get(rawurl); err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if body, err = getResponse(response); err != nil {
		return nil, err
	}
	err = json.Unmarshal(body, &rv)
	return &rv, err
}
开发者ID:vichetuc,项目名称:dropbox,代码行数:29,代码来源:dropbox.go

示例9: WaitHTTP

// WaitHTTP waits until http available
func (c *Container) WaitHTTP(port int, path string, timeout time.Duration) int {
	p := c.ports[port]
	if p == 0 {
		log.Fatalf("port %d is not exposed on %s", port, c.image)
	}
	now := time.Now()
	end := now.Add(timeout)
	for {
		cli := http.Client{Timeout: timeout}
		res, err := cli.Get("http://" + c.Addr(port) + path)
		if err != nil {
			if time.Now().After(end) {
				log.Fatalf("http not available on port %d for %s err:%v", port, c.image, err)
			}
			// sleep 1 sec to retry
			time.Sleep(1 * time.Second)
			continue
		}
		defer res.Body.Close()
		if res.StatusCode < 200 || res.StatusCode >= 300 {
			if time.Now().After(end) {
				log.Fatalf("http has not valid status code on port %d for %s code:%d", port, c.image, res.StatusCode)
			}
			// sleep 1 sec to retry
			time.Sleep(1 * time.Second)
			continue
		}
		break
	}
	return p
}
开发者ID:yorito,项目名称:dockertest,代码行数:32,代码来源:docker.go

示例10: 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

示例11: retrieveQueue

func retrieveQueue(client *http.Client, uri string, queue chan string) {
	fmt.Println("fetching: " + uri + " ...")
	var added = make(map[string]bool)
	resp, err := client.Get(uri)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	added[uri] = true
	// fmt.Println("uri visited is: ", uri)
	// fmt.Println("type of uri: ", reflect.TypeOf(uri))

	links := collectlinks.All(resp.Body)
	for _, link := range links {
		absolute := fixURL(link, uri)
		// fmt.Println("ab visited is: ", absolute)
		if absolute != "" && !added[absolute] {
			// fmt.Println("type of ab: ", reflect.TypeOf(absolute))
			added[absolute] = true
			go func() { queue <- absolute }()
		}
	}

}
开发者ID:sim4life,项目名称:go_poc,代码行数:25,代码来源:krawl.go

示例12: Example_serviceAccounts

func Example_serviceAccounts() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	config, err := google.NewServiceAccountConfig(&oauth2.JWTOptions{
		Email: "[email protected]",
		// PEMFilename. If you have a p12 file instead, you
		// can use `openssl` to export the private key into a pem file.
		// $ openssl pkcs12 -in key.p12 -out key.pem -nodes
		PEMFilename: "/path/to/pem/file.pem",
		Scopes: []string{
			"https://www.googleapis.com/auth/bigquery",
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	// Initiate an http.Client, the following GET request will be
	// authorized and authenticated on the behalf of
	// [email protected]
	client := http.Client{Transport: config.NewTransport()}
	client.Get("...")

	// If you would like to impersonate a user, you can
	// create a transport with a subject. The following GET
	// request will be made on the behalf of [email protected]
	client = http.Client{Transport: config.NewTransportWithUser("[email protected]")}
	client.Get("...")
}
开发者ID:rheimbuch,项目名称:oauth2,代码行数:29,代码来源:example_test.go

示例13: Example_webServer

func Example_webServer() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	config, err := google.NewConfig(&oauth2.Options{
		ClientID:     "YOUR_CLIENT_ID",
		ClientSecret: "YOUR_CLIENT_SECRET",
		RedirectURL:  "YOUR_REDIRECT_URL",
		Scopes: []string{
			"https://www.googleapis.com/auth/bigquery",
			"https://www.googleapis.com/auth/blogger"},
	})
	if err != nil {
		log.Fatal(err)
	}

	// Redirect user to Google's consent page to ask for permission
	// for the scopes specified above.
	url := config.AuthCodeURL("")
	fmt.Printf("Visit the URL for the auth dialog: %v", url)

	// Handle the exchange code to initiate a transport
	t, err := config.NewTransportWithCode("exchange-code")
	if err != nil {
		log.Fatal(err)
	}
	client := http.Client{Transport: t}
	client.Get("...")
}
开发者ID:rheimbuch,项目名称:oauth2,代码行数:28,代码来源:example_test.go

示例14: Ping

// Ping pings the host,
// it returns the response HTTP status code, body and error
func (h Host) Ping(c *http.Client) (int, []byte, error) {
	res, err := c.Get(h.Url)
	if err != nil {
		return 0, nil, err
	}

	defer res.Body.Close()

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return 0, nil, err
	}

	// compare the body
	if h.ExpectedBody != "" && string(b) != h.ExpectedBody {
		err = ErrBodyMismatch
	}

	// compare the status code
	if h.ExpectedStatusCode != 0 && h.ExpectedStatusCode != res.StatusCode {
		err = ErrStatusCodeMismatch
	} else if h.ExpectedStatusCode == 0 && res.StatusCode != 200 {
		err = ErrBadStatusCode
	}

	return res.StatusCode, b, err
}
开发者ID:mehulsbhatt,项目名称:pinger-1,代码行数:29,代码来源:host.go

示例15: get

// get performs an HTTPS GET to the specified path for a specific node.
func get(t *testing.T, client *http.Client, node *localcluster.Container, path string) []byte {
	url := fmt.Sprintf("https://%s%s", node.Addr(""), path)
	// There seems to be some issues while trying to connect to the status
	// server, so retry (up to 5 times) with a 1 second delay each time.
	// TODO(Bram): Clean this up once we get to the bottom of the issue.
	for r := retry.Start(retryOptions); r.Next(); {
		resp, err := client.Get(url)
		if err != nil {
			t.Logf("could not GET %s - %s", url, err)
			continue
		}
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Logf("could not open body for %s - %s", url, err)
			continue
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			t.Logf("could not GET %s - statuscode: %d - body: %s", url, resp.StatusCode, body)
			continue
		}
		t.Logf("OK response from %s", url)
		return body
	}
	t.Fatalf("There was an error retrieving %s", url)
	return []byte("")
}
开发者ID:shitfSign,项目名称:cockroach,代码行数:28,代码来源:status_server_test.go


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