當前位置: 首頁>>代碼示例>>Golang>>正文


Golang gorequest.New函數代碼示例

本文整理匯總了Golang中github.com/parnurzeal/gorequest.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: runRevokeTokenTest

func runRevokeTokenTest(t *testing.T, strategy oauth2.AccessTokenStrategy) {
	f := compose.Compose(new(compose.Config), fositeStore, strategy, compose.OAuth2ClientCredentialsGrantFactory, compose.OAuth2TokenIntrospectionFactory, compose.OAuth2TokenRevocationFactory)
	ts := mockServer(t, f, &fosite.DefaultSession{})
	defer ts.Close()

	oauthClient := newOAuth2AppClient(ts)
	token, err := oauthClient.Token(goauth.NoContext)
	assert.Nil(t, err)

	resp, _, errs := gorequest.New().Post(ts.URL+"/revoke").
		SetBasicAuth(oauthClient.ClientID, oauthClient.ClientSecret).
		Type("form").
		SendStruct(map[string]string{"token": "asdf"}).End()
	assert.Len(t, errs, 0)
	assert.Equal(t, 200, resp.StatusCode)

	resp, _, errs = gorequest.New().Post(ts.URL+"/revoke").
		SetBasicAuth(oauthClient.ClientID, oauthClient.ClientSecret).
		Type("form").
		SendStruct(map[string]string{"token": token.AccessToken}).End()
	assert.Len(t, errs, 0)
	assert.Equal(t, 200, resp.StatusCode)

	hres, _, errs := gorequest.New().Get(ts.URL+"/info").
		Set("Authorization", "bearer "+token.AccessToken).
		End()
	require.Len(t, errs, 0)
	assert.Equal(t, http.StatusUnauthorized, hres.StatusCode)
}
開發者ID:cristiangraz,項目名稱:fosite,代碼行數:29,代碼來源:revoke_token_test.go

示例2: init

func init() {
	resp, body, err := gorequest.New().
		Get("http://" + config.DbConfig.ServerRoot + ":" +
			strconv.FormatUint(uint64(config.DbConfig.Port), 10) +
			"/listDatabases").End()
	if err != nil {
		fmt.Println("listDatabase error:", err)
		os.Exit(1)
	}
	if resp.StatusCode != 200 {
		fmt.Println("listDatabase status:", resp.Status)
		os.Exit(1)
	}
	type dblist struct {
		Databases []string `json: "databases"`
	}
	var list dblist
	json.Unmarshal([]byte(body), &list)
	found := false
	for _, db := range list.Databases {
		if db == config.DATABASE {
			found = true
			break
		}
	}

	fmt.Println("found database is", found)
	if found == false {
		resp, body, err = gorequest.New().Post("http://" +
			config.DbConf(config.DbConfig).String() +
			"/database/" + config.DATABASE + "/plocal/document").End()
		if err != nil {
			fmt.Println("create database:", err)
		} else {
			fmt.Println(body)
			fmt.Println(resp.Status)
			fmt.Println("Database created")
			gorequest.New().Post("http://" + config.DbConf(config.DbConfig).String() + "/class/" + config.DATABASE + "/" + config.PASTECLASS).End()
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.USER_ID + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.TITLE + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.CONTENT + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.LANGUAGE + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.PUBLIC + " boolean")

		}
	} else {
		fmt.Println("Database already exists")
	}

}
開發者ID:RossBabcock3,項目名稱:gopastebin5,代碼行數:50,代碼來源:main.go

示例3: main

func main() {
	request := gorequest.New()
	_, body, _ := request.Get("http://127.0.0.1:4001/v2/keys/foo").End()
	fmt.Println(body)

	//IT WORKS!!
	save := gorequest.New()
	_, body2, _ := save.Put("http://127.0.0.1:4001/v2/keys/foo?value=hi").End()
	fmt.Println(body2)

	request = gorequest.New()
	_, body, _ = request.Get("http://127.0.0.1:4001/v2/keys/foo").End()
	fmt.Println(body)
}
開發者ID:hvescovi,項目名稱:learnGo,代碼行數:14,代碼來源:testApi2.go

示例4: getTeam

func getTeam(id int) {
	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IDOTA2Match_570/GetTeamInfoByTeamID/v0001/").
		Query("key=" + conf.Steamapi).
		Query("start_at_team_id=" + strconv.Itoa(id)).
		End()
	if errs != nil {
		log.Fatal(errs)
	}
	if resp.StatusCode != 200 {
		log.Println("(riki) ERROR:", resp.StatusCode)
		return
	}
	teamjs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}

	name := teamjs.Get("result").Get("teams").GetIndex(0).Get("name").MustString()
	tag := teamjs.Get("result").Get("teams").GetIndex(0).Get("tag").MustString()
	logo := teamjs.Get("result").Get("teams").GetIndex(0).Get("logo").MustInt()
	logo_sponsor := teamjs.Get("result").Get("teams").GetIndex(0).Get("logo_sponsor").MustInt()
	country_code := teamjs.Get("result").Get("teams").GetIndex(0).Get("country_code").MustString()
	url := teamjs.Get("result").Get("teams").GetIndex(0).Get("url").MustString()

	teamToSqlite(id, name, tag, logo, logo_sponsor, country_code, url)
}
開發者ID:shadow-blade-bot,項目名稱:riki,代碼行數:28,代碼來源:teams.go

示例5: httpGet

func (api cvedictClient) httpGet(key, url string, resChan chan<- response, errChan chan<- error) {
	var body string
	var errs []error
	var resp *http.Response
	f := func() (err error) {
		//  resp, body, errs = gorequest.New().SetDebug(config.Conf.Debug).Get(url).End()
		resp, body, errs = gorequest.New().Get(url).End()
		if 0 < len(errs) || resp == nil || resp.StatusCode != 200 {
			return fmt.Errorf("HTTP GET error: %v, url: %s, resp: %v", errs, url, resp)
		}
		return nil
	}
	notify := func(err error, t time.Duration) {
		log.Warnf("Failed to HTTP GET. retrying in %s seconds. err: %s", t, err)
	}
	err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify)
	if err != nil {
		errChan <- fmt.Errorf("HTTP Error %s", err)
	}
	cveDetail := cve.CveDetail{}
	if err := json.Unmarshal([]byte(body), &cveDetail); err != nil {
		errChan <- fmt.Errorf("Failed to Unmarshall. body: %s, err: %s", body, err)
	}
	resChan <- response{
		key,
		cveDetail,
	}
}
開發者ID:ymomoi,項目名稱:vuls,代碼行數:28,代碼來源:cve_client.go

示例6: Charge

// Charge - it charges the customer on mpower and returns a response json object which contains the receipt url with other information
// The `confirmToken` is from the customer
// Returns a `boolean` and `error`
// The boolean signifies whether the customer was chargeed or not
// The response json object can be retrieved on the onsite invoice object
//
// Example.
//    if ok, err := onsite.Charge(onsite.Token, "4346"); ok {
//      //doSomething
//    } else {
//
//    }
//
func (on *OnsiteInvoice) Charge(oprToken, confirmToken string) (bool, error) {
	var respData oprResponse
	data := opr{oprToken, confirmToken}
	req := gorequest.New()

	for key, val := range on.Setup.GetHeaders() {
		req.Set(key, val)
	}

	if dataByte, err := json.Marshal(data); err != nil {
		return false, err
	} else {
		if _, body, err := req.Send(bytes.NewBuffer(dataByte).String()).End(); err != nil {
			return false, fmt.Errorf("%v", err)
		} else {
			if err := json.Unmarshal(bytes.NewBufferString(body).Bytes(), &respData); err != nil {
				return false, err
			}

			on.ResponseText = respData.ResponseText
			on.ResponseCode = respData.ResponseCode

			if respData.ResponseCode == "00" {
				on.Description = respData.Description
				on.Status = respData.InvoiceData.Status
				on.ReceiptUrl = respData.InvoiceData.ReceiptUrl
				return true, nil
			} else {
				return false, fmt.Errorf("Failed to charge invoice. Check OPR or confirm token and try again.")
			}
		}
	}
}
開發者ID:MPowerPayments,項目名稱:mpowergo,代碼行數:46,代碼來源:onsite_invoice.go

示例7: sendRequest

func sendRequest(userName string, id int, jsonSchemaWithTag string) {
	request := gorequest.New()
	if tag, schema := stringify(jsonSchemaWithTag); tag == "" && schema == "" {
		fmt.Println("error")
	} else {
		str := `{"domainName":"` + userName + `","typeName":` + tag + `,"jsonSchema":` + schema + `}`

		fmt.Printf("%s", str)
		resp, _, err := request.Post(baseURL).
			Set("Content-Type", "application/json").
			Send(str).End()
		if err != nil {
			//spew.Dump(err)
			callBackUser(id, "JSON syntax error")
		} else {

			//	spew.Dump(body)
			//	spew.Dump(resp)
			target := Onion{}
			processResponser(resp, &target)
			spew.Dump(target.Ginger_Id)
			var s string = strconv.Itoa(int(target.Ginger_Id))
			sendRequestByIdForBuild(s, id)
		}
	}
}
開發者ID:mingderwang,項目名稱:twitterd,代碼行數:26,代碼來源:main.go

示例8: fetchHttp

func fetchHttp(url string, opts options) response {
	var resp gorequest.Response
	var body string
	var errs []error
	client := gorequest.New()
	switch opts.Method {
	case gorequest.HEAD:
		resp, body, errs = client.Head(url).End()
	case gorequest.GET:
		resp, body, errs = client.Get(url).End()
	case gorequest.POST:
		resp, body, errs = client.Post(url).Query(opts.Body).End()
	case gorequest.PUT:
		resp, body, errs = client.Put(url).Query(opts.Body).End()
	case gorequest.PATCH:
		resp, body, errs = client.Patch(url).Query(opts.Body).End()
	case gorequest.DELETE:
		resp, body, errs = client.Delete(url).End()
	}

	result := response{
		options:    opts,
		Status:     resp.StatusCode,
		StatusText: resp.Status,
		Errors:     errs,
	}
	result.Body = body
	result.Headers = resp.Header
	return result
}
開發者ID:deoxxa,項目名稱:go-duktape-fetch,代碼行數:30,代碼來源:fetch.go

示例9: Add

// Add exposes a container on the service
func (expose Expose) Add(name string, port int) error {
	var err error
	var query struct {
		LocalIP  string    `json:"localip"`
		Services []Service `json:"services"`
	}

	query.LocalIP, err = localIP()
	if err != nil {
		return err
	}

	query.Services = make([]Service, 1)
	query.Services[0].Service = expose.ContainerHost(name)
	query.Services[0].Port = port

	request := gorequest.New().Post("http://"+expose.url+"/api/service").
		Set("Auth-Username", expose.username).
		Set("Auth-Token", expose.token)
	res, _, errs := request.Send(query).End()

	if len(errs) > 0 {
		return errs[0]
	}

	if res.StatusCode != 200 {
		return fmt.Errorf("Invalid return code from server: %d\n%s", res.StatusCode, res.Body)
	}

	return nil
}
開發者ID:AerisCloud,項目名稱:docker-expose,代碼行數:32,代碼來源:expose.go

示例10: NewAPIPathwar

func NewAPIPathwar(token, debug string) *APIPathwar {
	return &APIPathwar{
		client: gorequest.New(),
		token:  token,
		debug:  debug != "",
	}
}
開發者ID:QuentinPerez,項目名稱:go-pathwar,代碼行數:7,代碼來源:api.go

示例11: UpdateRecords

func (z *Zone) UpdateRecords(rs []*Record) []error {
	c := RRsetContainer{
		RRsets: []*RRset{
			&RRset{
				Name: rs[0].Name, Type: rs[0].Type, ChangeType: "REPLACE",
				Records: rs,
			},
		},
	}

	_, bytes, errs := gorequest.
		New().
		Patch(fmt.Sprintf("%s/zones/%s", os.Getenv("API_URL"), z.Name)).
		Set("X-API-Key", os.Getenv("API_KEY")).
		Send(c).
		EndBytes()

	if errs != nil {
		return errs
	}
	err := json.Unmarshal(bytes, z)
	if err != nil {
		return []error{err}
	}

	return nil
}
開發者ID:epicagency,項目名稱:pdns-manager,代碼行數:27,代碼來源:zones.go

示例12: isValidAuthorizeRequest

func isValidAuthorizeRequest(c *HTTPClient, ar *AuthorizeRequest, retry bool) (bool, error) {
	request := gorequest.New()
	resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/guard/allowed")).SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).Set("Content-Type", "application/json").Send(*ar).End()
	if len(errs) > 0 {
		return false, errors.Errorf("Got errors: %v", errs)
	} else if retry && resp.StatusCode == http.StatusUnauthorized {
		var err error
		if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
			return false, errors.New(err)
		} else if c.clientToken == nil {
			return false, errors.New("Access token could not be retrieved")
		}
		return isValidAuthorizeRequest(c, ar, false)
	} else if resp.StatusCode != http.StatusOK {
		return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
	}

	if err := json.Unmarshal([]byte(body), &isAllowed); err != nil {
		return false, errors.Errorf("Could not unmarshall body because %s", err.Error())
	}

	if !isAllowed.Allowed {
		return false, errors.New("Authroization denied")
	}
	return isAllowed.Allowed, nil
}
開發者ID:emmanuel,項目名稱:hydra,代碼行數:26,代碼來源:client.go

示例13: isValidAuthenticationRequest

func isValidAuthenticationRequest(c *HTTPClient, token string, retry bool) (bool, error) {
	data := url.Values{}
	data.Set("token", token)
	request := gorequest.New()
	resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/oauth2/introspect")).Type("form").SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).SendString(data.Encode()).End()
	if len(errs) > 0 {
		return false, errors.Errorf("Got errors: %v", errs)
	} else if resp.StatusCode != http.StatusOK {
		return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
	}

	if retry && resp.StatusCode == http.StatusUnauthorized {
		var err error
		if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
			return false, errors.New(err)
		} else if c.clientToken == nil {
			return false, errors.New("Access token could not be retrieved")
		}
		return isValidAuthenticationRequest(c, token, false)
	} else if resp.StatusCode != http.StatusOK {
		return false, fmt.Errorf("Status code %d is not 200", resp.StatusCode)
	}

	var introspect struct {
		Active bool `json:"active"`
	}

	if err := json.Unmarshal([]byte(body), &introspect); err != nil {
		return false, err
	} else if !introspect.Active {
		return false, errors.New("Authentication denied")
	}
	return introspect.Active, nil
}
開發者ID:emmanuel,項目名稱:hydra,代碼行數:34,代碼來源:client.go

示例14: getLeaguePrizePool

func getLeaguePrizePool(leagueid int) {
	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IEconDOTA2_570/GetTournamentPrizePool/v0001/").
		Query("key=" + conf.Steamapi).
		Query("leagueid=" + strconv.Itoa(leagueid)).
		End()
	if errs != nil {
		log.Fatal(errs)
	}
	if resp.StatusCode != 200 {
		log.Println("(riki) ERROR:", resp.StatusCode)
		return
	}
	pooljs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}

	prize_pool := pooljs.Get("result").Get("prize_pool").MustInt()

	_, err = db.Exec("update leagues set prize_pool=? where id = ?;", prize_pool, leagueid)
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}
}
開發者ID:shadow-blade-bot,項目名稱:riki,代碼行數:27,代碼來源:leagues.go

示例15: getHeroes

//
// GetHeroes to SQLite db
//
func getHeroes() {

	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/").
		Query("key=" + conf.Steamapi).
		Query("language=en_us").
		End()
	if errs != nil {
		log.Fatal(errs)
	}
	herojs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}
	if resp.StatusCode != 200 {
		log.Println("(riki) ERROR:", resp.StatusCode)
		return
	}

	for i := range herojs.Get("result").Get("heroes").MustArray() {
		id := herojs.Get("result").Get("heroes").GetIndex(i).Get("id").MustInt()
		name := herojs.Get("result").Get("heroes").GetIndex(i).Get("name").MustString()
		localized_name := herojs.Get("result").Get("heroes").GetIndex(i).Get("localized_name").MustString()
		heroToSqlite(id, name[14:], localized_name)
	}
}
開發者ID:shadow-blade-bot,項目名稱:riki,代碼行數:30,代碼來源:heroes.go


注:本文中的github.com/parnurzeal/gorequest.New函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。