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)) }
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 }
// 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 }
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)) } }
// 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 }
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 }
// 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 }
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 }
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 }
// 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 }
// 统计数据 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 }
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) }
// 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 }
// 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 }) }
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://%x@%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() }
func (e *Endpoint) Think(state *common.RobotState) (*common.RobotCommands, error) { timeout := time.Duration(5 * time.Second) client := http.Client{ Timeout: timeout, } u, err := url.Parse(e.Root) if err != nil { return nil, err } u.Path = "think" log.Println("Making request to ", u.String()) js, _ := json.Marshal(state) r, err := client.Post(u.String(), "application/json", bytes.NewBuffer(js)) if err != nil { return nil, err } if r.StatusCode != http.StatusOK { return nil, errors.New(fmt.Sprintf("expected HTTP 200 - OK, got %v", r.StatusCode)) } else { log.Println("OK") } decoder := json.NewDecoder(r.Body) message := &common.RobotCommands{} err = decoder.Decode(message) if err != nil { log.Println(err) return nil, err } return message, nil }
func (p *payload) deliver() error { if len(p.APIKey) != 32 { return fmt.Errorf("bugsnag/payload.deliver: invalid api key") } buf, err := json.Marshal(p) if err != nil { return fmt.Errorf("bugsnag/payload.deliver: %v", err) } client := http.Client{ Transport: p.Transport, } resp, err := client.Post(p.Endpoint, "application/json", bytes.NewBuffer(buf)) if err != nil { return fmt.Errorf("bugsnag/payload.deliver: %v", err) } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("bugsnag/payload.deliver: Got HTTP %s\n", resp.Status) } return nil }
func (r *StdAlgTest) DoRequest(client *http.Client, resChan chan PerfResult) { var tpReq tpRequest tpReq.Points = make([]tpPoint, numPoints) for i := uint(0); i < numPoints; i++ { tpReq.Points[int(i)] = tpPoint{int32(random(lowerLat, upperLat) * 1.0e+7), int32(random(leftLon, rightLon) * 1.0e+7)} } tpReq.Constraints = make(map[string]interface{}) if constrained != "" { tpReq.Constraints[constrained] = intConstrained } b, err := json.Marshal(tpReq) if err != nil { fmt.Println(err) return } startTime := time.Now() response, err := client.Post(r.Server+"/alg"+algSuffix, "application/x-jackson-smile", bytes.NewBuffer(b)) if err != nil { fmt.Println(err) return } contentLength := response.ContentLength var length int if contentLength < 0 { length, err = response.Body.Read(r.buffer[:]) for err == nil { contentLength += int64(length) length, err = response.Body.Read(r.buffer[:]) } } response.Body.Close() resChan <- PerfResult{response.StatusCode, time.Since(startTime), contentLength} }
func sendUsageStats() { log.Trace("Sending anonymous usage stats to stats.grafana.org") version := strings.Replace(setting.BuildVersion, ".", "_", -1) metrics := map[string]interface{}{} report := map[string]interface{}{ "version": version, "metrics": metrics, } UsageStats.Each(func(name string, i interface{}) { switch metric := i.(type) { case Counter: if metric.Count() > 0 { metrics[name+".count"] = metric.Count() metric.Clear() } } }) statsQuery := m.GetSystemStatsQuery{} if err := bus.Dispatch(&statsQuery); err != nil { log.Error(3, "Failed to get system stats", err) return } metrics["stats.dashboards.count"] = statsQuery.Result.DashboardCount metrics["stats.users.count"] = statsQuery.Result.UserCount metrics["stats.orgs.count"] = statsQuery.Result.OrgCount metrics["stats.playlist.count"] = statsQuery.Result.PlaylistCount metrics["stats.plugins.apps.count"] = len(plugins.Apps) metrics["stats.plugins.panels.count"] = len(plugins.Panels) metrics["stats.plugins.datasources.count"] = len(plugins.DataSources) dsStats := m.GetDataSourceStatsQuery{} if err := bus.Dispatch(&dsStats); err != nil { log.Error(3, "Failed to get datasource stats", err) return } // send counters for each data source // but ignore any custom data sources // as sending that name could be sensitive information dsOtherCount := 0 for _, dsStat := range dsStats.Result { if m.IsKnownDataSourcePlugin(dsStat.Type) { metrics["stats.ds."+dsStat.Type+".count"] = dsStat.Count } else { dsOtherCount += dsStat.Count } } metrics["stats.ds.other.count"] = dsOtherCount out, _ := json.MarshalIndent(report, "", " ") data := bytes.NewBuffer(out) client := http.Client{Timeout: time.Duration(5 * time.Second)} go client.Post("https://stats.grafana.org/grafana-usage-report", "application/json", data) }
func (h *harness) postInOut(c *http.Client, s string, t *testing.T) string { res, err := c.Post(h.baseUrl+"inout", "text/plain", bytes.NewBuffer(([]byte)(s))) require.Nil(t, err) require.Equal(t, http.StatusOK, res.StatusCode) return readAll(res.Body, t) }
// POST the given JSON body to Rollbar synchronously. func post(body map[string]interface{}, httpClient *http.Client) { if len(Token) == 0 { stderr("empty token") return } jsonBody, err := json.Marshal(body) if err != nil { stderr("failed to encode payload: %s", err.Error()) return } if httpClient == nil { httpClient = &http.Client{} } resp, err := httpClient.Post(Endpoint, "application/json", bytes.NewReader(jsonBody)) if err != nil { stderr("POST failed: %s", err.Error()) return } else if resp.StatusCode != 200 { stderr("received response: %s", resp.Status) } if resp != nil { resp.Body.Close() } defer resp.Body.Close() }
// QueryResponse performs a v2 OpenTSDB request to the given host. host should // be of the form hostname:port. A nil client uses DefaultClient. func (r *Request) QueryResponse(host string, client *http.Client) (*http.Response, error) { u := url.URL{ Scheme: "http", Host: host, Path: "/api/query", } b, err := json.Marshal(&r) if err != nil { return nil, err } if client == nil { client = DefaultClient } resp, err := client.Post(u.String(), "application/json", bytes.NewReader(b)) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { e := RequestError{Request: string(b)} defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) if err := json.NewDecoder(bytes.NewBuffer(body)).Decode(&e); err == nil { return nil, &e } s := fmt.Sprintf("opentsdb: %s", resp.Status) if len(body) > 0 { s = fmt.Sprintf("%s: %s", s, body) } return nil, errors.New(s) } return resp, nil }
func reportLaunch() { json := fmt.Sprintf(`{"os": "%s", "arch": "%s", "gomaxprocs": %d, "numcpu": %d, "numshards": %d, "app": "ekanited"}`, runtime.GOOS, runtime.GOARCH, runtime.GOMAXPROCS(0), runtime.NumCPU(), numShards) 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) }
func RunAvailabilityScenario(url string, client *http.Client) error { resp, err := client.Post(url, "application/json", nil) if err != nil { return err } defer resp.Body.Close() return nil }
func getMonthPhotos(cxt appengine.Context, httpClient *http.Client, apiIndex int) (success bool, photos *Photos) { now := time.Now() year := now.Year() month := int(now.Month()) response, err := httpClient.Post(fmt.Sprintf("http://nasa-photo-dev%d.appspot.com/month_list", apiIndex), "application/json", bytes.NewBufferString(fmt.Sprintf(`{"reqId":"%s","year":%d, "month" : %d, "timeZone":"CET"}`, NewV4().String(), year, month))) return getPhotos(cxt, response, err) }
func (suite *RouterTestSuite) TestPostFail() { client := http.Client{} res, err := client.Post(suite.server.URL, "application/text", nil) if err != nil { suite.Fail("POST request failed", err) } res.Body.Close() suite.Equal(http.StatusBadRequest, res.StatusCode) }
func post_url(client *http.Client, url string, post_data string) (response []byte, header http.Header) { resp, err := client.Post(url, "application/x-www-form-urlencoded", strings.NewReader(post_data)) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) return body, resp.Header }
func (suite *RouterTestSuite) TestPost() { client := http.Client{} res, err := client.Post(suite.server.URL, "application/text", strings.NewReader(ResponseBody)) if err != nil { suite.Fail("POST request failed", err) } res.Body.Close() suite.Equal(http.StatusOK, res.StatusCode) }
// Ensure the server can handle a request. func TestHTTPServerRequest(t *testing.T) { addr := "localhost:64000" path := "/test" status := 200 request := "ping" response := "pong" uri := "http://" + addr + path requests := make(chan MockRequest, 1) defer close(requests) handler := NewMockHandler(t, status, []byte(response), requests) server := NewHTTPServer(addr, handler) wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() if err := server.ListenAndServe(); err != nil { t.Error(err) } }() time.Sleep(100 * time.Millisecond) client := http.Client{} rdr := bytes.NewReader([]byte(request)) if res, err := client.Post(uri, "text/plain", rdr); err == nil { if status != res.StatusCode { t.Errorf("response status is invalid: %d != %d", status, res.StatusCode) } if responseBody, err := ioutil.ReadAll(res.Body); err != nil { t.Error(err) } else if string(responseBody) != response { t.Errorf("response body is invalid: %s != %s", responseBody, response) } res.Body.Close() } else { t.Fatal(err) } req := <-requests if req.Method != "POST" { t.Errorf("request method invalid: %s != POST", req.Method) } if req.URL.Path != path { t.Errorf("request path invalid: %s != %s", req.URL.Path, path) } reqBody := string(req.Body) if reqBody != request { t.Errorf("request body invalid: %s != %s", reqBody, request) } if err := server.Close(); err != nil { t.Fatal(err) } wg.Wait() }
func TestOperationsList(t *testing.T) { testOver := make(chan struct{}) defer close(testOver) simpleStorage := &SimpleRESTStorage{ injectedFunction: func(obj runtime.Object) (runtime.Object, error) { // Eliminate flakes by ensuring the create operation takes longer than this test. <-testOver return obj, nil }, } handler := Handle(map[string]RESTStorage{ "foo": simpleStorage, }, codec, "/prefix", "version", selfLinker, admissionControl) handler.(*defaultAPIServer).group.handler.asyncOpWait = 0 server := httptest.NewServer(handler) defer server.Close() client := http.Client{} simple := &Simple{ ObjectMeta: api.ObjectMeta{Name: "foo"}, } data, err := codec.Encode(simple) if err != nil { t.Fatalf("unexpected error: %v", err) } response, err := client.Post(server.URL+"/prefix/version/foo", "application/json", bytes.NewBuffer(data)) if err != nil { t.Fatalf("unexpected error: %v", err) } if response.StatusCode != http.StatusAccepted { t.Fatalf("Unexpected response %#v", response) } response, err = client.Get(server.URL + "/prefix/version/operations") if err != nil { t.Fatalf("unexpected error: %v", err) } if response.StatusCode != http.StatusOK { t.Fatalf("unexpected status code %#v", response) } body, err := ioutil.ReadAll(response.Body) if err != nil { t.Fatalf("unexpected error: %v", err) } obj, err := codec.Decode(body) if err != nil { t.Errorf("unexpected error: %v", err) } oplist, ok := obj.(*api.OperationList) if !ok { t.Fatalf("expected ServerOpList, got %#v", obj) } if len(oplist.Items) != 1 { t.Errorf("expected 1 operation, got %#v", obj) } }