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


Golang Client.Post方法代码示例

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


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

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

示例2: Plusone

func Plusone(httpClient *http.Client, url string) (int, error) {
	resp, err := httpClient.Post(
		"https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ",
		"application/json",
		villa.NewPByteSlice([]byte(`[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id": "`+
			url+`","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]`)))
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	var v [1]struct {
		Result struct {
			Metadata struct {
				GlobalCounts struct {
					Count float64
				}
			}
		}
	}
	if err := dec.Decode(&v); err != nil {
		return 0, err
	}

	return int(0.5 + v[0].Result.Metadata.GlobalCounts.Count), nil
}
开发者ID:pombredanne,项目名称:gcse,代码行数:27,代码来源:crawler.go

示例3: Notify

// Notify will send the error and stack trace to Bugsnag. Note that this doesn't take advantage of all of Bugsnag's capabilities.
func Notify(config *Config, jobName string, eventName string, err error, trace *stack.Trace, kvs map[string]string) error {

	// Make a struct that serializes to the JSON needed for the API request to bugsnag
	p := newPayload(config, jobName, eventName, err, trace, kvs)

	// JSON serialize it
	data, err := json.MarshalIndent(p, "", "\t")
	if err != nil {
		return err
	}

	// Post it to the server:
	client := http.Client{}
	resp, err := client.Post(config.Endpoint, "application/json", bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	if string(body) != "OK" {
		return fmt.Errorf("response from bugsnag wasn't 'OK'")
	}

	return nil
}
开发者ID:leobcn,项目名称:health,代码行数:28,代码来源:api.go

示例4: sendMapToPipeviz

func sendMapToPipeviz(m *ingest.Message, r *git.Repository) {
	addr, err := GetTargetAddr(r)
	// Find the target pipeviz instance from the git config
	if err != nil {
		log.Fatalln("Could not find target address in config:", err)
	}

	msg, err := json.Marshal(m)
	if err != nil {
		log.Fatalln("JSON encoding failed with err:", err)
	}
	//dump, _ := json.MarshalIndent(m, "", "    ")
	//fmt.Println(string(dump))

	client := http.Client{Timeout: 3 * time.Second}
	resp, err := client.Post(addr, "application/json", bytes.NewReader(msg))
	if err != nil {
		log.Fatalln("Error on sending to server:", err)
	}

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		bod, err := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			log.Fatalf(err.Error())
		}

		log.Fatalln("Message rejected by pipeviz server: %v", string(bod))
	}
}
开发者ID:jeffsheltren,项目名称:pvgit,代码行数:30,代码来源:shared.go

示例5: Upload

// Upload uploads data to logstore and returns logPath.
// data will be compressed.
func Upload(client *http.Client, prefix string, data []byte) (string, error) {
	hd := sha256.Sum256(data)
	h := base64.URLEncoding.EncodeToString(hd[:])
	logPath := path.Join("upload", fmt.Sprintf("%s.%s.gz", prefix, h))
	var buf bytes.Buffer
	gw := gzip.NewWriter(&buf)
	gw.Write(data)
	err := gw.Close()
	if err != nil {
		return "", err
	}

	// https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#simple
	requrl := fmt.Sprintf(`https://www.googleapis.com/upload/storage/v1/b/chromium-build-stats.appspot.com/o?uploadType=media&name=%s`, logPath)
	resp, err := client.Post(requrl, "application/octet-data", bytes.NewReader(buf.Bytes()))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != 200 {
		return "", fmt.Errorf("upload status: %s %d %s: %s: %v", requrl, resp.StatusCode, resp.Status, body, err)
	}
	return logPath, nil
}
开发者ID:nicko96,项目名称:Chrome-Infra,代码行数:27,代码来源:upload.go

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

示例7: 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:TShadwell,项目名称:go-openid,代码行数:61,代码来源:verify.go

示例8: sendMatchData

func sendMatchData(src io.Reader, addr string) (MatchHash, error) {
	cl := http.Client{}

	url := fmt.Sprintf("http://%s/api/matches/new", addr)

	log.Printf("posting to URL: %s", url)

	resp, err := cl.Post(url, "application/vnd.q3-match-stats", src)
	if err != nil {
		return emptyHash, errors.Wrap(err, "posting match data failed")
	}

	log.Printf("response: %d", resp.StatusCode)

	if resp.StatusCode != http.StatusOK {
		return emptyHash, fmt.Errorf("request failed with status: %d",
			resp.StatusCode)
	}

	matchhash, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return emptyHash, errors.Wrap(err, "failed to receive response")
	}

	return MatchHash(matchhash), nil
}
开发者ID:bboozzoo,项目名称:q3stats,代码行数:26,代码来源:import.go

示例9: submitSerialRequest

func submitSerialRequest(t *state.Task, serialRequest string, client *http.Client) (*asserts.Serial, error) {
	st := t.State()
	st.Unlock()
	defer st.Lock()
	resp, err := client.Post(serialRequestURL, asserts.MediaType, bytes.NewBufferString(serialRequest))
	if err != nil {
		return nil, retryErr(t, "cannot deliver device serial request: %v", err)
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case 200, 201:
	case 202:
		return nil, errPoll
	default:
		return nil, retryErr(t, "cannot deliver device serial request: unexpected status %d", resp.StatusCode)
	}

	// decode body with serial assertion
	dec := asserts.NewDecoder(resp.Body)
	got, err := dec.Decode()
	if err != nil { // assume broken i/o
		return nil, retryErr(t, "cannot read response to request for a serial: %v", err)
	}

	serial, ok := got.(*asserts.Serial)
	if !ok {
		return nil, fmt.Errorf("cannot use device serial assertion of type %q", got.Type().Name)
	}

	return serial, nil
}
开发者ID:clobrano,项目名称:snappy,代码行数:32,代码来源:devicemgr.go

示例10: SendRequest

// SendRequest sends a SMS using provided SmsSendRequest structure.
func (self Session) SendRequest(request SmsSendRequest) (result *SmsSendResult, err error) {
	request.Login = self.Login
	request.Password = self.Password

	data, err := xml.Marshal(&request)
	if err != nil {
		return nil, err
	}

	client := http.Client{
		// Self-signed certificate workaround
		Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
	}
	response, err := client.Post(ServiceAddress, "application/xml", bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	data, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	result = &SmsSendResult{}
	err = xml.Unmarshal(data, result)
	if err != nil {
		return nil, err
	}

	if result.Code != 1 {
		return nil, &SendError{result.Code, result.CodeDescription}
	}
	return result, nil
}
开发者ID:lanior,项目名称:smsuslugi,代码行数:36,代码来源:smsuslugi.go

示例11: StatisticsData

// 统计数据
func StatisticsData(db, key, val, opt string) error {
	client := http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				deadline := time.Now().Add(10 * time.Second)
				c, err := net.DialTimeout(netw, addr, time.Second*10)
				if err != nil {
					return nil, err
				}
				c.SetDeadline(deadline)
				return c, nil
			},
		},
	}
	surl := GetConfVal("default::stats_url")
	v := url.Values{}
	v.Set("db", db)
	v.Set("key", key)
	v.Set("value", val)
	v.Set("opt", opt)

	res, err := client.Post(surl+"api/create", "application/x-www-form-urlencoded",
		ioutil.NopCloser(strings.NewReader(v.Encode())))
	if err != nil {
		return err
	}

	if res != nil && res.Body != nil {
		res.Body.Close()
	}
	return nil
}
开发者ID:qgweb,项目名称:new,代码行数:33,代码来源:fun.go

示例12: reportLaunch

func reportLaunch() {
	json := fmt.Sprintf(`{"os": "%s", "arch": "%s", "app": "gollector"}`, runtime.GOOS, runtime.GOARCH)
	data := bytes.NewBufferString(json)
	client := http.Client{Timeout: time.Duration(5 * time.Second)}
	go client.Post("https://logs-01.loggly.com/inputs/8a0edd84-92ba-46e4-ada8-c529d0f105af/tag/reporting/",
		"application/json", data)
}
开发者ID:appuri,项目名称:syslog-gollector,代码行数:7,代码来源:syslog-gollector.go

示例13: 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:LeXa4894,项目名称:test,代码行数:34,代码来源:http.go

示例14: ClientPost

// Retry wrapper for http://golang.org/pkg/net/http/#Client.Post where attempts is the number of http calls made (one plus number of retries).
func (httpRetryClient *Client) ClientPost(c *http.Client, url string, bodyType string, body []byte) (resp *http.Response, attempts int, err error) {
	return httpRetryClient.Retry(func() (*http.Response, error, error) {
		resp, err := c.Post(url, bodyType, bytes.NewBuffer(body))
		// assume all errors should result in a retry
		return resp, err, nil
	})
}
开发者ID:taskcluster,项目名称:taskcluster-worker,代码行数:8,代码来源:httpbackoff.go

示例15: sendBadBlockReport

func sendBadBlockReport(block *types.Block, err error) {
	if !EnableBadBlockReporting {
		return
	}

	var (
		blockRLP, _ = rlp.EncodeToBytes(block)
		params      = map[string]interface{}{
			"block":     common.Bytes2Hex(blockRLP),
			"blockHash": block.Hash().Hex(),
			"errortype": err.Error(),
			"client":    "go",
		}
	)
	if !block.ReceivedAt.IsZero() {
		params["receivedAt"] = block.ReceivedAt.UTC().String()
	}
	if p, ok := block.ReceivedFrom.(*peer); ok {
		params["receivedFrom"] = map[string]interface{}{
			"enode":           fmt.Sprintf("enode://%[email protected]%v", p.ID(), p.RemoteAddr()),
			"name":            p.Name(),
			"protocolVersion": p.version,
		}
	}
	jsonStr, _ := json.Marshal(map[string]interface{}{"method": "eth_badBlock", "id": "1", "jsonrpc": "2.0", "params": []interface{}{params}})
	client := http.Client{Timeout: 8 * time.Second}
	resp, err := client.Post(badBlocksURL, "application/json", bytes.NewReader(jsonStr))
	if err != nil {
		glog.V(logger.Debug).Infoln(err)
		return
	}
	glog.V(logger.Debug).Infof("Bad Block Report posted (%d)", resp.StatusCode)
	resp.Body.Close()
}
开发者ID:Codzart,项目名称:go-ethereum,代码行数:34,代码来源:bad_block.go


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