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 }
func authenticateWithBackend(req *http.Request) (bool, error) { auth, authExists := req.Header["Authorization"] if authExists && isCached(auth[0]) { return true, nil } var r *http.Request var err error var resp *http.Response r, err = http.NewRequest("GET", planio_url, nil) if err != nil { return false, err } r.Header["Authorization"] = auth client := http.Client{} resp, err = client.Do(r) if err != nil { return false, err } resp.Body.Close() if resp.StatusCode == 200 { if authExists { addToCache(auth[0]) } return true, nil } return false, nil }
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 }
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() } }
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 (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) }
func TestWatchHTTPAccept(t *testing.T) { simpleStorage := &SimpleRESTStorage{} handler := handle(map[string]rest.Storage{"simples": simpleStorage}) server := httptest.NewServer(handler) defer server.Close() client := http.Client{} dest, _ := url.Parse(server.URL) dest.Path = "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simples" dest.RawQuery = "" request, err := http.NewRequest("GET", dest.String(), nil) if err != nil { t.Errorf("unexpected error: %v", err) } request.Header.Set("Accept", "application/XYZ") response, err := client.Do(request) if err != nil { t.Errorf("unexpected error: %v", err) } // TODO: once this is fixed, this test will change if response.StatusCode != http.StatusNotAcceptable { t.Errorf("Unexpected response %#v", response) } }
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 }
func asyncHttpGets(urls []string) []*HttpResponse { ch := make(chan *HttpResponse) responses := []*HttpResponse{} client := http.Client{} for _, url := range urls { go func(url string) { fmt.Printf("Fetching %s \n", url) resp, err := client.Get(url) ch <- &HttpResponse{url, resp, err} if err != nil && resp != nil && resp.StatusCode == http.StatusOK { resp.Body.Close() } }(url) } for { select { case r := <-ch: fmt.Printf("%s was fetched\n", r.url) if r.err != nil { fmt.Println("with an error", r.err) } responses = append(responses, r) if len(responses) == len(urls) { return responses } case <-time.After(50 * time.Millisecond): fmt.Printf(".") } } return responses }
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 }
func (g *Adaptor) ExpireTokens(userID int) error { request := ExpireTokenRequest{Action: "all"} gandalfUrl := fmt.Sprintf("http://%s:%d/expire/%d", g.GandalfHost, g.GandalfPort, userID) client := http.Client{} marshalledReq, err := json.Marshal(request) if err != nil { return err } req, err := http.NewRequest("POST", gandalfUrl, bytes.NewBuffer(marshalledReq)) if err != nil { return err } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return errors.New("failed to expire tokens") } return nil }
// GetCookieConfig returns settings needed to set a Crowd SSO cookie. func (c *Crowd) GetCookieConfig() (CookieConfig, error) { cc := CookieConfig{} client := http.Client{Jar: c.cookies} req, err := http.NewRequest("GET", c.url+"rest/usermanagement/1/config/cookie", nil) if err != nil { return cc, err } req.SetBasicAuth(c.user, c.passwd) req.Header.Set("Accept", "application/xml") req.Header.Set("Content-Type", "application/xml") resp, err := client.Do(req) if err != nil { return cc, err } defer resp.Body.Close() if resp.StatusCode != 200 { return cc, fmt.Errorf("request failed: %s\n", resp.Status) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return cc, err } err = xml.Unmarshal(body, &cc) if err != nil { return cc, err } return cc, nil }
func getLeaderStatus(tr *http.Transport, endpoints []string) (string, raftStatus, error) { // TODO: use new etcd client httpclient := http.Client{ Transport: tr, } for _, ep := range endpoints { resp, err := httpclient.Get(ep + "/debug/vars") if err != nil { continue } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { continue } vs := &vars{} d := json.NewDecoder(resp.Body) err = d.Decode(vs) if err != nil { continue } if vs.RaftStatus.Lead != vs.RaftStatus.ID { continue } return ep, vs.RaftStatus, nil } return "", raftStatus{}, errors.New("no leader") }
// PublicKey requests a shadowfax server's public key. An error is returned // if the server URL is not https. func PublicKey(serverURL string, client *http.Client) (*sf.PublicKey, error) { u, err := url.Parse(serverURL) if err != nil { return nil, errgo.Mask(err, errgo.Any) } if u.Scheme != "https" { return nil, errgo.Newf("public key must be requested with https") } if client == nil { client = http.DefaultClient } req, err := http.NewRequest("GET", serverURL+"/publickey", nil) if err != nil { return nil, errgo.Mask(err) } resp, err := client.Do(req) if err != nil { return nil, errgo.Mask(err) } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) var publicKeyResp wire.PublicKeyResponse err = dec.Decode(&publicKeyResp) if err != nil { return nil, errgo.Mask(err) } publicKey, err := sf.DecodePublicKey(publicKeyResp.PublicKey) if err != nil { return nil, errgo.Mask(err) } return publicKey, nil }
// makeRequest is a wrapper function used for making DNS API requests func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) { url := c.cloudDNSEndpoint + uri req, err := http.NewRequest(method, url, body) if err != nil { return nil, err } req.Header.Set("X-Auth-Token", c.token) req.Header.Set("Content-Type", "application/json") client := http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("Error querying DNS API: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted { return nil, fmt.Errorf("Request failed for %s %s. Response code: %d", method, url, resp.StatusCode) } var r json.RawMessage err = json.NewDecoder(resp.Body).Decode(&r) if err != nil { return nil, fmt.Errorf("JSON decode failed for %s %s. Response code: %d", method, url, resp.StatusCode) } return r, nil }
// 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 }
func normalGet(method string, c *http.Client, url *url.URL) { if c == nil { c = http.DefaultClient } if *verbose { log.Printf("%s %s", method, url) } req, err := http.NewRequest(method, url.String(), nil) if err != nil { log.Fatal(err) } resp, err := c.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } if !(resp.StatusCode >= 200 && resp.StatusCode <= 399) { log.Fatalf("Error: HTTP %d: %s.", resp.StatusCode, body) } fmt.Println(string(body)) }
func HandleCompletedTask(logger lager.Logger, httpClient *http.Client, taskDB db.TaskDB, task *models.Task) { logger = logger.Session("handle-completed-task", lager.Data{"task_guid": task.TaskGuid}) if task.CompletionCallbackUrl != "" { modelErr := taskDB.ResolvingTask(logger, task.TaskGuid) if modelErr != nil { logger.Error("marking-task-as-resolving-failed", modelErr) return } logger = logger.WithData(lager.Data{"callback_url": task.CompletionCallbackUrl}) json, err := json.Marshal(&models.TaskCallbackResponse{ TaskGuid: task.TaskGuid, Failed: task.Failed, FailureReason: task.FailureReason, Result: task.Result, Annotation: task.Annotation, CreatedAt: task.CreatedAt, }) if err != nil { logger.Error("marshalling-task-failed", err) return } var statusCode int for i := 0; i < MAX_CB_RETRIES; i++ { request, err := http.NewRequest("POST", task.CompletionCallbackUrl, bytes.NewReader(json)) if err != nil { logger.Error("building-request-failed", err) return } request.Header.Set("Content-Type", "application/json") response, err := httpClient.Do(request) if err != nil { matched, _ := regexp.MatchString("Client.Timeout|use of closed network connection", err.Error()) if matched { continue } logger.Error("doing-request-failed", err) return } defer response.Body.Close() statusCode = response.StatusCode if shouldResolve(statusCode) { modelErr := taskDB.DeleteTask(logger, task.TaskGuid) if modelErr != nil { logger.Error("delete-task-failed", modelErr) } return } } logger.Info("callback-failed", lager.Data{"status_code": statusCode}) } return }
func test() { var client *http.Client tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client = &http.Client{tr, nil, nil, 0 * time.Second} req, err := http.NewRequest("GET", "", nil) if err != nil { fmt.Println("response: ", err) return } resp, err := client.Do(req) if err != nil { fmt.Println("response2: ", err) return } reader := bufio.NewReader(resp.Body) defer resp.Body.Close() //delim := []byte("\n") for { line, err := reader.ReadString('\n') if err != nil { fmt.Println("response3: ", err) return } else { fmt.Printf("resp:%s\n", line) } } }
// Do sends an HTTP request with the provided http.Client and returns an HTTP response. // If the client is nil, http.DefaultClient is used. // If the context is canceled or times out, ctx.Err() will be returned. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. cancel := canceler(client, req) type responseAndError struct { resp *http.Response err error } result := make(chan responseAndError, 1) go func() { resp, err := client.Do(req) result <- responseAndError{resp, err} }() select { case <-ctx.Done(): cancel() return nil, ctx.Err() case r := <-result: return r.resp, r.err } }
func GrantVoteResponse(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { vote = p.ByName("vote") //ch <- 1 fmt.Println("Vote received:", vote) if vote == "true" { voteCount++ } fmt.Println(voteCount) if voteCount > total/2 && state != "leader" { fmt.Println("Leader....") state = "leader" myDetails := MyDetails{} myDetails.IsLeader = true myDetails.IP = "localhost" //enter the IP address myDetails.Port = "3001" //enter the port number myDeatilsInJSON, _ := json.Marshal(myDetails) myDetailsBuff := new(bytes.Buffer) err := binary.Write(myDetailsBuff, binary.BigEndian, &myDeatilsInJSON) if err != nil { fmt.Errorf("Error in request API: %v", err) } url := fmt.Sprintf("http://localhost:9999/setleader") client := http.Client{} req, _ := http.NewRequest("POST", url, myDetailsBuff) res, _ := client.Do(req) res.Body.Close() NotifyFollowers() //DK } }
// not follow redirect.... func Gethtml3(url string) { client := new(http.Client) request, _ := http.NewRequest("GET", "http://www.baidu.com", nil) request.Header.Add("Accept-Encoding", "gzip") response, _ := client.Do(request) defer response.Body.Close() for k, v := range response.Header { fmt.Println(k) fmt.Println(v) } // Check that the server actually sent compressed data var reader io.ReadCloser switch response.Header.Get("Content-Encoding") { case "gzip": fmt.Println("XXXXXXXXXX gzip") reader, _ = gzip.NewReader(response.Body) defer reader.Close() default: reader = response.Body } var s string if b, err := ioutil.ReadAll(reader); err == nil { s = string(b) } println(s) }
// Check if docker (or dogestry) is running on the endpoint func ServerCheck(host string, port int, timeout time.Duration, docker bool) bool { url := fmt.Sprintf("http://%v:%v/version", host, port) if !docker { url = fmt.Sprintf("http://%v:%v/status/check", host, port) } client := http.Client{ Timeout: timeout, } resp, getErr := client.Get(url) if getErr != nil { return false } defer resp.Body.Close() if docker { if resp.StatusCode != 200 { return false } } else { // Dogestry check body, readErr := ioutil.ReadAll(resp.Body) if readErr != nil { return false } if string(body) != "OK" { return false } } return true }
// 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) // TODO(bram) #2059: Remove retry logic. 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 } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Logf("could not read body for %s - %s", url, err) continue } 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("") }
// initRobotAccount creates a GCP robot account for this connector. func initRobotAccount(userClient *http.Client) (string, string) { params := url.Values{} params.Set("oauth_client_id", flagToString(gcpOAuthClientIDFlag, lib.DefaultConfig.GCPOAuthClientID)) url := fmt.Sprintf("%s%s?%s", flagToString(gcpBaseURLFlag, lib.DefaultConfig.GCPBaseURL), "createrobot", params.Encode()) response, err := userClient.Get(url) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatal("failed to initialize robot account: " + response.Status) } var robotInit struct { Success bool `json:"success"` Message string `json:"message"` XMPPJID string `json:"xmpp_jid"` AuthCode string `json:"authorization_code"` } if err = json.NewDecoder(response.Body).Decode(&robotInit); err != nil { log.Fatal(err) } if !robotInit.Success { log.Fatal("failed to initialize robot account: " + robotInit.Message) } fmt.Println("Requested OAuth credentials for robot account") return robotInit.XMPPJID, robotInit.AuthCode }
func getUserInfo(target_name string) UserInfo { bearer := getToken() url := "https://api.twitter.com/1.1/users/show.json?screen_name=" + target_name request, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearer)) client := new(http.Client) response, err := client.Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) util.Perror(err) var user_info UserInfo parse_err := json.Unmarshal(body, &user_info) util.Perror(parse_err) return user_info }
// GetMetaData retrieves instance metadata about the current machine. // // See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html for more details. func GetMetaData(path string) (contents []byte, err error) { c := http.Client{ Transport: &http.Transport{ Dial: func(netw, addr string) (net.Conn, error) { deadline := time.Now().Add(5 * time.Second) c, err := net.DialTimeout(netw, addr, time.Second*2) if err != nil { return nil, err } c.SetDeadline(deadline) return c, nil }, }, } url := "http://169.254.169.254/latest/meta-data/" + path resp, err := c.Get(url) if err != nil { return } defer resp.Body.Close() if resp.StatusCode != 200 { err = fmt.Errorf("Code %d returned for url %s", resp.StatusCode, url) return } body, err := ioutil.ReadAll(resp.Body) if err != nil { return } return []byte(body), err }
func (c *Client) request(client *http.Client, credentials *Credentials, urlStr string, params url.Values) (*Credentials, url.Values, error) { c.SignParam(credentials, "POST", urlStr, params) resp, err := client.PostForm(urlStr, params) if err != nil { return nil, nil, err } p, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return nil, nil, err } if resp.StatusCode != 200 { return nil, nil, fmt.Errorf("OAuth server status %d, %s", resp.StatusCode, string(p)) } vals, err := url.ParseQuery(string(p)) if err != nil { return nil, nil, err } credentials = &Credentials{ Token: vals.Get("oauth_token"), Secret: vals.Get("oauth_token_secret"), } if credentials.Token == "" { return nil, nil, errors.New("No OAuth token in server result") } if credentials.Secret == "" { return nil, nil, errors.New("No OAuth secret in server result") } return credentials, vals, nil }
func main() { var longUrl string longUrl = os.Args[len(os.Args)-1] body := bytes.NewBufferString(fmt.Sprintf(`{"longUrl":"%s"}`, longUrl)) request, err := http.NewRequest("POST", "https://www.googleapis.com/urlshortener/v1/url", body) request.Header.Add("Content-Type", "application/json") client := http.Client{} response, err := client.Do(request) if err != nil { log.Fatal(err) } outputAsBytes, err := ioutil.ReadAll(response.Body) response.Body.Close() var output apiResponse err = json.Unmarshal(outputAsBytes, &output) if err != nil { log.Fatal(err) } fmt.Printf("%s\n", output.Id) }
func (q *Queue) notify(t *Task) error { if t.callback == "" { return nil } buf := bytes.Buffer{} if t.output != nil { if err := json.NewEncoder(&buf).Encode(t.output); err != nil { return err } } t.backoff.Reset() var ( err error resp *http.Response ) client := http.Client{ Timeout: 5 * time.Second, } req, err := http.NewRequest("POST", t.callback, &buf) if err != nil { panic(err) } req.Header.Set("content-type", "application/json") if t.token != "" { req.Header.Set("token", t.token) } // Attempt to notify multiple times. for i := 0; i < NotifyAttempts; i++ { resp, err = client.Do(req) if err != nil { continue } // 200 range, good to go. if resp.StatusCode > 200 && resp.StatusCode < 300 { return nil } time.Sleep(t.backoff.Duration()) } // Error making the request. if err != nil { return err } // HTTP error. return fmt.Errorf("Notify error: %q", resp.Status) }