func main() { cert, err := tls.LoadX509KeyPair("../cert.pem", "../key.pem") if err != nil { log.Fatalln("Unable to load cert", err) } clientCACert, err := ioutil.ReadFile("../cert.pem") if err != nil { log.Fatal("Unable to open cert", err) } clientCertPool := x509.NewCertPool() clientCertPool.AppendCertsFromPEM(clientCACert) tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: clientCertPool, } tlsConfig.BuildNameToCertificate() ro := &grequests.RequestOptions{ HTTPClient: &http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, }, } resp, err := grequests.Get("https://localhost:8080", ro) if err != nil { log.Println("Unable to speak to our server", err) } log.Println(resp.String()) }
func ListServerApp() { if !Ping() { Login() } var ro = &grequests.RequestOptions{ Headers: map[string]string{"Cookie": cookie}, } rsp, err := grequests.Get(hubHost+"/api/holes/", ro) if err != nil { log.Fatal(err) } defer rsp.Close() if !rsp.Ok { log.Fatalf("Error: %s\n", rsp.String()) } var holeApps map[string][]HoleApp err = rsp.JSON(&holeApps) fmt.Println("ID\t\t\t\t\tName\t\tPort\t\t\t\t\tStatus") var holeApp, rh HoleApp for _, rh = range holeApps["holes"] { holeApp, err = NewHoleApp(rh.ID) if err != nil { holeApp = rh } fmt.Printf("%s\t%s\t\t%s:%s/%s->%s:%s/%s\t%s\n", holeApp.ID, holeApp.Name, holeApp.Lhost, holeApp.Lport, holeApp.Lscheme, holeApp.Host, holeApp.Port, holeApp.Scheme, holeApp.Status) } }
func Example_cookies() { resp, err := grequests.Get("http://httpbin.org/cookies", &grequests.RequestOptions{ Cookies: []http.Cookie{ { Name: "TestCookie", Value: "Random Value", HttpOnly: true, Secure: false, }, { Name: "AnotherCookie", Value: "Some Value", HttpOnly: true, Secure: false, }, }, }) if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } log.Println(resp.String()) }
// Setup download selected version to target dir and unpacks it func (v *Version) Setup(rootDir string) error { sdkRoot := filepath.Join(rootDir, v.Release) os.MkdirAll(sdkRoot, 0755) targetFile := filepath.Join(rootDir, v.name) if _, err := os.Stat(targetFile); os.IsNotExist(err) { resp, err := req.Get( v.remoteURL, &req.RequestOptions{ UserAgent: "Mozilla/5.0 (compatible; Gobu; +https://github.com/dz0ny/gobu)", }, ) if err != nil { return err } log.Infoln("Starting download of ", v.String()) err = resp.DownloadToFile(targetFile) if err != nil { return err } log.Infoln("Starting extraction of ", targetFile) if strings.HasSuffix(v.name, ".zip") { return archive.Unzip(targetFile, sdkRoot) } if strings.HasSuffix(v.name, ".tar.gz") { return archive.Untar(targetFile, sdkRoot) } return errors.New("Unsuported archive type") } return nil }
func (p Ping) Gather(self serf.Member, e serf.Event) error { // TODO check http response p.logger.Info("inspecting HTTP endpoint: %s", p.Endpoint) resp, err := grequests.Get(p.Endpoint, nil) if err != nil || !resp.Ok { p.logger.Error("failed to ping endpoint: %s", err) return p.notify(err) } return nil }
func Example_acceptInvalidTLSCert() { ro := &grequests.RequestOptions{InsecureSkipVerify: true} resp, err := grequests.Get("https://www.pcwebshop.co.uk/", ro) if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } }
func Example_basicAuth() { ro := &grequests.RequestOptions{Auth: []string{"Levi", "Bot"}} resp, err := grequests.Get("http://httpbin.org/get", ro) // Not the usual JSON so copy and paste from below if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } }
func Example_customUserAgent() { ro := &grequests.RequestOptions{UserAgent: "LeviBot 0.1"} resp, err := grequests.Get("http://httpbin.org/get", ro) if err != nil { log.Fatal("Oops something went wrong: ", err) } if resp.Ok != true { log.Println("Request did not return OK") } log.Println(resp.String()) }
func Example_customHTTPHeader() { ro := &grequests.RequestOptions{UserAgent: "LeviBot 0.1", Headers: map[string]string{"X-Wonderful-Header": "1"}} resp, err := grequests.Get("http://httpbin.org/get", ro) // Not the usual JSON so copy and paste from below if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } }
func Example_basicGetCustomHTTPClient() { // This is a very basic GET request resp, err := grequests.Get("http://httpbin.org/get", &grequests.RequestOptions{HTTPClient: http.DefaultClient}) if err != nil { log.Println(err) } if resp.Ok != true { log.Println("Request did not return OK") } log.Println(resp.String()) }
func (client *Client) get(path string, options *grequests.RequestOptions) (*simplejson.Json, error) { if options == nil { options = client.provider.options() } resp, err := grequests.Get(client.provider.baseURL()+path, options) if err != nil { return nil, err } if !resp.Ok { return nil, NewErrorFromBody(resp.String()) } return simplejson.NewFromReader(resp) }
func Example_basicGet() { // This is a very basic GET request resp, err := grequests.Get("http://httpbin.org/get", nil) if err != nil { log.Println(err) } if resp.Ok != true { log.Println("Request did not return OK") } log.Println(resp.String()) }
func Example_urlQueryParams() { ro := &grequests.RequestOptions{ Params: map[string]string{"Hello": "World", "Goodbye": "World"}, } resp, err := grequests.Get("http://httpbin.org/get", ro) // url will now be http://httpbin.org/get?hello=world&goodbye=world if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } }
// FetchRepo will download the boilerplate from remote and extract to ${appName}/ folder func FetchRepo(t int, appName string, appID string) error { utils.CheckError(os.Mkdir(appName, 0700)) repoURL := map[int]string{ Python: "http://lcinternal-cloud-code-update.leanapp.cn/python-getting-started.zip", NodeJS: "http://lcinternal-cloud-code-update.leanapp.cn/node-js-getting-started.zip", }[t] dir, err := ioutil.TempDir("", "leanengine") utils.CheckError(err) defer os.RemoveAll(dir) log.Println("正在下载项目模版...") resp, err := grequests.Get(repoURL, nil) if err != nil { return err } defer resp.Close() if resp.StatusCode != 200 { return errors.New(utils.FormatServerErrorResult(resp.String())) } log.Println("下载完成") zipFilePath := filepath.Join(dir, "getting-started.zip") resp.DownloadToFile(zipFilePath) log.Println("正在创建项目...") zipFile, err := zip.OpenReader(zipFilePath) utils.CheckError(err) defer zipFile.Close() for _, f := range zipFile.File { err := extractAndWriteFile(f, appName) if err != nil { return err } } if err := apps.AddApp(appName, appName, appID); err != nil { return err } log.Println("创建项目完成") return nil }
func main() { response, err := grequests.Get("http://127.0.0.1:3000/register", nil) if err != nil { panic("Unable to register:" + err.Error()) } respdata := strings.Split(response.String(), ",") id := respdata[0] clienttest := respdata[1] worker, err := gowork.NewWorker("w4PYxQjVP9ZStjWpBt5t28CEBmRs8NPx", id, clienttest) testresponse, err := grequests.Post("http://127.0.0.1:3000/verify", &grequests.RequestOptions{Params: map[string]string{"id": id, "clientresp": worker.Verification.ClientResponse}}) if err != nil { panic("Unable to verify:" + err.Error()) } worker = worker.SetAuthenticationKey(testresponse.String()) fmt.Println(worker.SessionAuthenticationKey) }
func (client *Client) getJSON(path string, options *grequests.RequestOptions) (interface{}, error) { if options == nil { options = client.provider.options() } resp, err := grequests.Get(client.provider.baseURL()+path, options) if err != nil { return nil, err } if !resp.Ok { return nil, NewErrorFromBody(resp.String()) } var result interface{} err = resp.JSON(&result) return result, err }
func GetAddress(zipcode string) address { resp, err := grequests.Get(GOOGLE_MAPS_API_ENDPOINT, &grequests.RequestOptions{ Params: map[string]string{ "language": "ja", "address": zipcode, }, }) if err != nil { log.Fatalln("Unable to make request: ", err) } var a googleAddress err = json.Unmarshal(resp.Bytes(), &a) if err != nil { log.Println("google address json unmarshal error: ", err) return address{ Error: "google address json unmarshal error", } } if len(a.Results) < 1 || len(a.Results[0].AddressComponents) < 5 { log.Println("google address json unmarshal error: ", err) return address{ Error: "no results found", } } components := a.Results[0].AddressComponents components = components[:len(components)-1] //remove country components = components[1:len(components)] //remove zipcode result := address{} result.Area = components[len(components)-1].LongName result.City = components[len(components)-2].LongName //concatenate remaining components to form address string addressString := "" for i := len(components) - 3; i >= 0; i-- { addressString += components[i].LongName } result.Address = addressString return result }
func Example_proxy() { proxyURL, err := url.Parse("http://127.0.0.1:8080") // Proxy URL if err != nil { log.Panicln(err) } resp, err := grequests.Get("http://www.levigross.com/", &grequests.RequestOptions{Proxies: map[string]*url.URL{proxyURL.Scheme: proxyURL}}) if err != nil { log.Println(err) } if resp.Ok != true { log.Println("Request did not return OK") } log.Println(resp) }
func getCert(name, outName string) { var ro = &grequests.RequestOptions{ Headers: map[string]string{"Cookie": cookie}, } rsp, err := grequests.Get(hubHost+"/api/"+name, ro) if err != nil { log.Fatal(err) } defer rsp.Close() if !rsp.Ok { log.Fatalf("Error: %s\n", rsp.String()) } fp, _ := os.Create(outName) io.Copy(fp, rsp) fp.Close() }
// Update fetches and updates version's for current GOOS and GOARCH func (r *Remote) Update() { if r.data == "" { resp, err := req.Get( "https://golang.org/dl", &req.RequestOptions{ UserAgent: "Mozilla/5.0 (compatible; Gobu; +https://github.com/dz0ny/gobu)", }, ) if err != nil { log.Fatalln("Unable to make request:", err) } r.data = resp.String() } for _, v := range r.parseDownloads(r.data) { if v.Compatible() { r.Versions = append(r.Versions, v) } } }
func Example_downloadFile() { resp, err := grequests.Get("http://httpbin.org/get", nil) if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } if err := resp.DownloadToFile("randomFile"); err != nil { log.Println("Unable to download to file: ", err) } if err != nil { log.Println("Unable to download file", err) } }
func Ping() bool { var ro = &grequests.RequestOptions{ Headers: map[string]string{"Cookie": cookie}, } rsp, err := grequests.Get(hubHost+"/api/ping/", ro) if err != nil { log.Fatal(err) } defer rsp.Close() if !rsp.Ok { log.Fatalf("Error: %s\n", rsp.String()) } var pong = true if rsp.String() == "false" { pong = false } return pong }
func (server *Server) getFunctions() ([]string, error) { url := fmt.Sprintf("http://localhost:%s/1.1/functions/_ops/metadatas", server.AppPort) response, err := grequests.Get(url, &grequests.RequestOptions{ Headers: map[string]string{ "x-avoscloud-application-id": server.AppID, "x-avoscloud-master-key": server.MasterKey, }, }) if err != nil { return nil, err } result := new(struct { Result []string `json:"result"` }) err = response.JSON(result) if err != nil { return nil, err } return result.Result, nil }
func Example_parse_XML() { type GetXMLSample struct { XMLName xml.Name `xml:"slideshow"` Title string `xml:"title,attr"` Date string `xml:"date,attr"` Author string `xml:"author,attr"` Slide []struct { Type string `xml:"type,attr"` Title string `xml:"title"` } `xml:"slide"` } resp, err := grequests.Get("http://httpbin.org/xml", nil) if err != nil { log.Println("Unable to make request", err) } if resp.Ok != true { log.Println("Request did not return OK") } userXML := &GetXMLSample{} // func xmlASCIIDecoder(charset string, input io.Reader) (io.Reader, error) { // return input, nil // } // If the server returns XML encoded in another charset (not UTF-8) – you // must provide an encoder function that looks like the one I wrote above. // If you an consuming UTF-8 just pass `nil` into the second arg if err := resp.XML(userXML, xmlASCIIDecoder); err != nil { log.Println("Unable to consume the response as XML: ", err) } if userXML.Title != "Sample Slide Show" { log.Printf("Invalid XML serialization %#v", userXML) } }
func main() { log.Println("Starting execution...") // Create a file to which the program will write oFile, oErr := os.Create("outfile.txt") if oErr != nil { log.Fatalf("ERROR: Error creating an output file see: %v\nEnding processing.", oErr) } defer oFile.Close() // Import the yaml file data lErr := loadRequests("data/calldata.toml") if lErr != nil { log.Fatalf("ERROR: Error loading TOML data see: %v\nEnding processing.", lErr) } // Iterate through the request data for i := 0; i < len(cData.Requests); i++ { log.Printf("INFO: Working on request #: %v\n", i+1) var madeReq bool // Construct the next request var myReq grequests.RequestOptions var myResp *grequests.Response // Assign any parameters myReq.Params = cData.Requests[i].Params // Determine the method myReq.Data = cData.Requests[i].Params switch cData.Requests[i].Method { case "GET": myResp, _ = grequests.Get(cData.Requests[i].URL, &myReq) madeReq = true case "POST": // Configure the ResponseOption for the applicable body and body type pErr := roBody(&myReq, &cData.Requests[i]) if pErr != nil { log.Printf("Error: configuring the POST request body\n") } else { myResp, _ = grequests.Post(cData.Requests[i].URL, &myReq) madeReq = true } default: log.Printf("ERROR: Can't determine the request method") } // Print out the respsonse if madeReq == true { myRawRespStr, _, _ := utils.DumpResponse(myResp.RawResponse) // Format a string to be written to the output file oStr := fmt.Sprintf("\n\n******\n\nThe response to #: %v is:\n\n%v\n\n*****\n\n", i, myRawRespStr) // Write the output string _, wErr := oFile.WriteString(oStr) if wErr != nil { log.Printf("ERROR: Writing the response to the output file see: %v\n", wErr) } } } log.Println("Ending execution...") }
func (c *Client) GetTagRecent(tag string) (*grequests.Response, error) { url := fmt.Sprintf("https://api.instagram.com/v1/tags/%v/media/recent", tag) options := c.options() return grequests.Get(url, options) }
func (c *Client) GetUser(id string) (*grequests.Response, error) { url := fmt.Sprintf("https://api.instagram.com/v1/users/%v", id) options := c.options() return grequests.Get(url, options) }