本文整理汇总了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))
}
示例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
}
示例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
}
示例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))
}
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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
})
}
示例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()
}