當前位置: 首頁>>代碼示例>>Golang>>正文


Golang http.Client類代碼示例

本文整理匯總了Golang中http.Client的典型用法代碼示例。如果您正苦於以下問題:Golang Client類的具體用法?Golang Client怎麽用?Golang Client使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Client類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: downloadBlob

func (self *Federation) downloadBlob(rawurl, blobref string) (dependencies []string, err os.Error) {
	// Get the blob
	var client http.Client
	req, err := client.Get(rawurl + "?blobref=" + http.URLEscape(blobref))
	if err != nil {
		return nil, err
	}
	// TODO: Improve for large files
	blob, err := ioutil.ReadAll(req.Body)
	if err != nil {
		log.Printf("Error reading request body")
		return nil, err
	}
	log.Printf("Downloaded %v\n", string(blob))
	req.Body.Close()
	self.store.StoreBlob(blob, "")
	// Check whether the retrieved blob is a schema blob
	mimetype := grapher.MimeType(blob)
	if mimetype == "application/x-lightwave-schema" {
		var schema depSchema
		err = json.Unmarshal(blob, &schema)
		if err != nil {
			log.Printf("Malformed schema blob: %v\n", err)
			return nil, err
		}
		dependencies = schema.Dependencies
	}
	return
}
開發者ID:AaronO,項目名稱:lightwave,代碼行數:29,代碼來源:federation.go

示例2: postPhoto

// postPhoto uses the Buzz API to post the image to the user's Buzz stream.
func postPhoto(client *http.Client, photoURL string) error {
	const url = "https://www.googleapis.com/buzz/v1/activities/@me/@self"
	const text = "Moustachio"

	type m map[string]interface{}
	post := m{"data": m{"object": m{
		"type":    "note",
		"content": text,
		"attachments": []m{{
			"type":    "photo",
			"content": text,
			"links": m{
				"enclosure": []m{{
					"href": photoURL,
					"type": "image/jpeg",
				}},
			},
		}},
	}}}

	b, err := json.Marshal(post)
	if err != nil {
		return err
	}
	resp, err := client.Post(url, "application/json", bytes.NewBuffer(b))
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return errors.New("invalid post " + resp.Status)
	}
	return nil
}
開發者ID:ashokgelal,項目名稱:gorilla,代碼行數:34,代碼來源:http.go

示例3: VerifyValues

// Like Verify on a parsed URL
func VerifyValues(values url.Values) (grant bool, identifier string, err error) {
	err = nil

	var postArgs url.Values
	postArgs = url.Values(map[string][]string{})

	// Create the url
	URLEndPoint := values.Get("openid.op_endpoint")
	if URLEndPoint == "" {
		log.Printf("no openid.op_endpoint")
		return false, "", errors.New("no openid.op_endpoint")
	}
	for k, v := range values {
		postArgs[k] = v
	}
	postArgs.Set("openid.mode", "check_authentication")
	postContent := postArgs.Encode()

	// Post the request
	var client = new(http.Client)
	postReader := bytes.NewBuffer([]byte(postContent))
	response, err := client.Post(URLEndPoint, "application/x-www-form-urlencoded", postReader)
	if err != nil {
		log.Printf("VerifyValues failed at post")
		return false, "", err
	}

	// Parse the response
	// Convert the reader
	// We limit the size of the response to 1024 bytes but it should be large enough for most cases
	buffer := make([]byte, 1024)
	_, err = response.Body.Read(buffer)
	if err != nil {
		log.Printf("VerifyValues failed reading response")
		return false, "", err
	}

	// Check for ns
	rematch := REVerifyDirectNs.FindSubmatch(buffer)
	if rematch == nil {
		return false, "", errors.New("VerifyValues: ns value not found on the response of the OP")
	}
	nsValue := string(rematch[1])
	if !bytes.Equal([]byte(nsValue), []byte("http://specs.openid.net/auth/2.0")) {
		return false, "", errors.New("VerifyValues: ns value not correct: " + nsValue)
	}

	// Check for is_valid
	match, err := regexp.Match(REVerifyDirectIsValid, buffer)
	if err != nil {
		return false, "", err
	}

	identifier = values.Get("openid.claimed_id")
	if !match {
		log.Printf("no is_valid:true in \"%s\"", buffer)
	}

	return match, identifier, nil
}
開發者ID:tobi,項目名稱:go-openid,代碼行數:61,代碼來源:verify.go

示例4: GetTrendingRepositories

func GetTrendingRepositories(client *http.Client) ([]Repository, os.Error) {
	resp, e := client.Get("https://www.github.com/explore")
	if e != nil {
		return nil, e
	}
	rootnode, e := html.Parse(resp.Body)
	if e != nil {
		return nil, e
	}

	list := make([]Repository, 0, 5)
	listnode := findNextNodeWithClass(rootnode, "ranked-repositories")
	for _, item := range listnode.Child {
		repo := findNextNodeWithTag(item, "h3")
		if repo != nil && !hasClass("last", item) {
			owner := repo.Child[1].Child[0].Data
			name := repo.Child[3].Child[0].Data
			list = append(list, Repository{
				User: owner,
				Name: name,
			})
		}
	}
	return list, nil

}
開發者ID:surma-dump,項目名稱:trendinghubs,代碼行數:26,代碼來源:main.go

示例5: put

// Send an HTTP PUT request.  The caller is responsible for calling
// resp.Body.Close().
func put(client *http.Client, url, data string) (resp *http.Response, err os.Error) {
	req, err := http.NewRequest("PUT", url, strings.NewReader(data))
	if err != nil {
		return
	}
	resp, err = client.Do(req)
	return
}
開發者ID:emk,項目名稱:cstore,代碼行數:10,代碼來源:cstore_test.go

示例6: fetchXMLFeed

func fetchXMLFeed(url string) string {
	client := http.Client{}
	response, err := client.Get(url)
	if err != nil {
		return ""
	}
	defer response.Body.Close()
	return readAllContents(response.Body)
}
開發者ID:acj,項目名稱:go-guardian-pics,代碼行數:9,代碼來源:fetch_gallery.go

示例7: assertHttpGetStatus

func assertHttpGetStatus(t *testing.T, client *http.Client, code int, url string) {
	r, err := client.Get(url)
	if err != nil {
		t.Errorf("Can't GET %v: %v", url, err)
		return
	}
	defer r.Body.Close()
	if r.StatusCode != code {
		t.Errorf("Expected status %v, got %v", code, r.Status)
	}
}
開發者ID:emk,項目名稱:cstore,代碼行數:11,代碼來源:cstore_test.go

示例8: printNum

func printNum(i int, c *http.Client, ch chan int) {
	url := fmt.Sprintf("http://www.reddit.com?count=%d", i)
	resp, _ := c.Get(url)
	defer resp.Body.Close()

	readBytes, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("Status: %s, Bytes: %d\n", resp.Status, len(readBytes))
	ch <- 1

	//fmt.Print(byteString(readBytes))
}
開發者ID:evilcore,項目名稱:sandbox,代碼行數:11,代碼來源:goroutine.go

示例9: sickle_lookup

func sickle_lookup(u, p, q_name string, q *Queue) {
	url := sickleUrl + "/lookup?username=" + u + "&password=" + p + "&queue_name=" + q_name
	client := new(http.Client)
	resp, _, _ := client.Get(url)
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode == 404 {
		fmt.Println("could not find queue")
	}
	json.Unmarshal(body, q)
	return
}
開發者ID:ryandotsmith,項目名稱:qman,代碼行數:11,代碼來源:qman.go

示例10: PostActivity

func PostActivity(activity *Activity, bearerToken string, client *http.Client) {
	outputJSON, _ := json.Marshal(activity)
	request, _ := http.NewRequest("POST", "https://api.runkeeper.com/fitnessActivities", strings.NewReader(string(outputJSON)))
	request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
	request.Header.Add("Content-Type", "application/vnd.com.runkeeper.NewFitnessActivity+json")
	response, _ := client.Do(request)
	if response.StatusCode == 201 {
		fmt.Print("Activity POSTed")
	} else {
		fmt.Printf("Activity post failed with status code %d and message %s", response.StatusCode, response.Body)
	}
}
開發者ID:eedrummer,項目名稱:go-run-outside,代碼行數:12,代碼來源:runkeeper.go

示例11: send

// Sign and send a Request using the current configuration.
func (c *UserConfig) send(request *http.Request, service *Service, client *http.Client) (*http.Response, os.Error) {
	if err := service.Sign(request, c); err != nil {
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	if response.StatusCode != 200 {
		return nil, os.NewError("Endpoint response: " + response.Status)
	}
	return response, nil
}
開發者ID:paul-lalonde,項目名稱:golibs,代碼行數:14,代碼來源:userconfig.go

示例12: assertHttpGet

func assertHttpGet(t *testing.T, client *http.Client, expected, url string) {
	r, err := client.Get(url)
	if err != nil {
		t.Errorf("Can't GET %v: %v", url, err)
		return
	}
	defer r.Body.Close()
	if r.StatusCode != http.StatusOK {
		t.Errorf("Unexpected HTTP status: %v", r.Status)
		return
	}
	assertResponseBody(t, expected, r)
}
開發者ID:emk,項目名稱:cstore,代碼行數:13,代碼來源:cstore_test.go

示例13: TestIntegration

func TestIntegration(t *testing.T) {
	service, userConfig := GetTwitterConfig(t)
	httpClient := new(http.Client)
	url := "https://api.twitter.com/1/account/verify_credentials.json"
	httpRequest, _ := http.NewRequest("GET", url, nil)
	service.Sign(httpRequest, userConfig)
	httpResponse, err := httpClient.Do(httpRequest)
	if err != nil {
		t.Error("Response had an error")
	}
	if httpResponse.StatusCode != 200 {
		t.Errorf("Response returned code of %v", httpResponse.StatusCode)
	}
}
開發者ID:paul-lalonde,項目名稱:golibs,代碼行數:14,代碼來源:oauth1a_test_integration.go

示例14: send

func (this *Neo4j) send(url string, data string) (string, os.Error) {
	var (
		resp *http.Response // http response
		buf  bytes.Buffer   // contains http response body
		err  os.Error
	)
	if len(url) < 1 {
		url = this.URL + "node" // default path
	}
	client := new(http.Client)
	switch strings.ToLower(this.Method) { // which http method
	case "delete":
		req, e := http.NewRequest("DELETE", url, nil)
		if e != nil {
			err = e
			break
		}
		resp, err = client.Do(req)
	case "post":
		body := strings.NewReader(data)
		resp, err = client.Post(url,
			"application/json",
			body,
		)
	case "put":
		body := strings.NewReader(data)
		req, e := http.NewRequest("PUT", url, body)
		if e != nil {
			err = e
			break
		}
		req.Header.Set("Content-Type", "application/json")
		resp, err = client.Do(req)
	case "get":
		fallthrough
	default:
		resp, err = client.Get(url)
	}
	if err != nil {
		return "", err
	}
	defer func() {
		if resp.Body != nil {
			resp.Body.Close()
		}
	}()
	_, err = buf.ReadFrom(resp.Body)
	if err != nil {
		return "", err
	}
	this.StatusCode = resp.StatusCode // the calling method should do more inspection with chkStatusCode() method and determine if the operation was successful or not.
	return buf.String(), nil
}
開發者ID:searchify,項目名稱:Neo4j-GO,代碼行數:53,代碼來源:neo4j.go

示例15: FetchVueSp

/*
récupère la vue d'un troll.
Renvoie des SoapItem pour la compatibilité avec la fonction FetchVueSoap.
Utilise le TksManager pour renseigner le nom du troll qui n'est pas renvoyé par le sp.
Paramètres avecTresors, avecLieux : 0 ou 1
*/
func FetchVueSp(numero uint, mdp_restreint string, avecTresors uint, avecLieux uint, tksManager *TksManager) (items []*SoapItem, errorDetails string) {
	httpClient := new(http.Client)
	request := fmt.Sprintf("http://sp.mountyhall.com/SP_Vue2.php?Numero=%d&Motdepasse=%s&Tresors=%d&Lieux=%d", numero, mdp_restreint, avecTresors, avecLieux)
	resp, err := httpClient.Get(request)
	if err != nil {
		errorDetails = err.String()
		return
	}
	defer resp.Body.Close()
	r := bufio.NewReader(resp.Body)
	bline, _, _ := r.ReadLine()
	line := string(bline)
	currentType := ""
	for line != "" {
		if line[0] == '#' {
			tokens := strings.Split(line, " ", 2)
			if tokens[0] == "#DEBUT" && len(tokens) > 1 {
				currentType = (tokens[1])[0 : len(tokens[1])-1]
			}
		} else {
			tokens := strings.Split(line, ";", 5)
			//fmt.Printf(" %s %+v\n", currentType, tokens)
			item := new(SoapItem)
			item.Numero, _ = strconv.Atoi(tokens[0])
			if item.Numero > 0 {
				if currentType == "TROLL" && len(tokens) > 3 {
					item.Nom, _, _ = tksManager.GetNomRaceNiveauTroll(item.Numero)
					item.PositionX, _ = strconv.Atoi(tokens[1])
					item.PositionY, _ = strconv.Atoi(tokens[2])
					item.PositionN, _ = strconv.Atoi(tokens[3])
				} else if len(tokens) > 4 {
					item.Nom = AsciiToUTF8([]uint8(tokens[1]))
					item.PositionX, _ = strconv.Atoi(tokens[2])
					item.PositionY, _ = strconv.Atoi(tokens[3])
					item.PositionN, _ = strconv.Atoi(tokens[4])
				}
				if item.Nom != "" && currentType != "" {
					item.Type = currentType
					items = append(items, item)
				}
			}
		}
		bline, _, _ = r.ReadLine()
		line = string(bline)
	}
	return
}
開發者ID:Chouia,項目名稱:Chrall,代碼行數:53,代碼來源:mhspclient.go


注:本文中的http.Client類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。