本文整理汇总了Golang中github.com/google/go-querystring/query.Values函数的典型用法代码示例。如果您正苦于以下问题:Golang Values函数的具体用法?Golang Values怎么用?Golang Values使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Values函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: constructQueryString
func constructQueryString(data interface{}) (string, error) {
v, err := query.Values(data)
if err != nil {
return "", nil
}
return v.Encode(), nil
}
开发者ID:faildep,项目名称:faildep-httpclient,代码行数:7,代码来源:httpclient.go
示例2: EditUserProfile
func (a *Adaptor) EditUserProfile(userProfile *client.UserProfile) (bool, *adaptor.AdaptorError) {
var editSuccess int
params, queryErr := query.Values(userProfile)
if queryErr != nil {
ln.Err("error query user profile", ln.Map{"err": queryErr.Error()})
return false, adaptor.NewError("error query user profile")
}
err := a.apidClient.DoFunction("editUserProfile", params, &editSuccess)
if err != nil {
ln.Err("error updating user profile", ln.Map{"err": err.Error(), "user_profile": userProfile})
return false, adaptor.NewError("error updating user profile")
}
if editSuccess == 0 {
// check if the user exists
user, adaptorError := a.GetUserProfile(userProfile.UserID)
if adaptorError != nil {
ln.Err("error when getting user profile", ln.Map{"err": adaptorError.Error(), "user_id": userProfile.UserID})
return false, adaptor.NewError("error when getting user profile")
}
if user == nil {
return false, adaptor.NewErrorWithStatus("user profile not found", http.StatusNotFound)
}
// no fields were changed
return true, nil
}
return true, nil
}
开发者ID:john-cai,项目名称:tools,代码行数:34,代码来源:provision.go
示例3: TestEncodeDecodeQuery
func TestEncodeDecodeQuery(t *testing.T) {
const expected = "entities=c%2F1&entities=c%2F2&origin=mysystem"
q := Query{}
q.Origin = "mysystem"
q.Entities = []string{"c/1", "c/2"}
v, err := query.Values(q)
if err != nil {
t.Fatal(err)
}
t.Log(v.Encode())
if v.Encode() != expected {
t.Fatalf("Expected %s, got %s", expected, v.Encode())
}
q2 := new(Query)
decoder := schema.NewDecoder()
err = decoder.Decode(q2, v)
if err != nil {
t.Fatal(err)
}
if q.Origin != q2.Origin {
t.Fatalf("Expected %s, got %s", q.Origin, q2.Origin)
}
}
开发者ID:straumur,项目名称:straumur,代码行数:32,代码来源:query_test.go
示例4: GetRequestURI
func (r *Request) GetRequestURI() (*url.URL, error) {
queryParams, err := query.Values(r)
if err != nil {
return nil, err
}
return url.ParseRequestURI(fmt.Sprintf("%s?%s", APIURL, queryParams.Encode()))
}
开发者ID:netbrain,项目名称:gopixabay,代码行数:7,代码来源:request.go
示例5: List
func (cli *OpsGenieAlertClient) List(req alerts.ListAlertsRequest) (*alerts.ListAlertsResponse, error) {
req.ApiKey = cli.apiKey
// validate the mandatory parameter: apiKey
if req.ApiKey == "" {
return nil, errors.New("ApiKey is a mandatory field and can not be empty.")
}
v, _ := goquery.Values(req)
var resp *goreq.Response
var err error
for i := 0; i < cli.retries; i++ {
resp, err = cli.buildRequest("GET", LIST_ALERTS_URL+"?"+v.Encode(), nil).Do()
if err == nil {
break
}
time.Sleep(TIME_SLEEP_BETWEEN_REQUESTS)
}
if err != nil {
return nil, errors.New("Could not retrieve the alert: a problem occured while sending the request")
}
// check the returning HTTP status code
httpStatusCode := resp.StatusCode
if httpStatusCode >= 400 && httpStatusCode < 500 {
return nil, errors.New(fmt.Sprintf("Client error %d returned", httpStatusCode))
}
if httpStatusCode >= 500 {
return nil, errors.New(fmt.Sprintf("Server error %d returned", httpStatusCode))
}
var listAlertsResp alerts.ListAlertsResponse
// check if the response can be unmarshalled
if err = resp.Body.FromJsonTo(&listAlertsResp); err != nil {
return nil, errors.New("Server response can not be parsed.")
}
return &listAlertsResp, nil
}
开发者ID:ryane,项目名称:consul-alerts,代码行数:34,代码来源:opsgenie_alert_client.go
示例6: addRouteOptions
// addOptions adds the parameters in opt as URL query parameters to s. opt
// must be a struct whose fields may contain "url" tags.
func addRouteOptions(route string, options interface{}) (*url.URL, error) {
Debug(DbgInfo, "Adding options %+v to route '%s'\n", options, route)
u, err := url.Parse(route)
if err != nil {
Debug(DbgError, "url.Parse(%s) error: %s\n", route, err)
errStr := wski18n.T("Unable to parse URL '{{.route}}': {{.err}}",
map[string]interface{}{"route": route, "err": err})
werr := MakeWskError(errors.New(errStr), EXITCODE_ERR_GENERAL, DISPLAY_MSG, NO_DISPLAY_USAGE)
return nil, werr
}
v := reflect.ValueOf(options)
if v.Kind() == reflect.Ptr && v.IsNil() {
return u, nil
}
qs, err := query.Values(options)
if err != nil {
Debug(DbgError, "query.Values(%#v) error: %s\n", options, err)
errStr := wski18n.T("Unable to process URL query options '{{.options}}': {{.err}}",
map[string]interface{}{"options": fmt.Sprintf("%#v", options), "err": err})
werr := MakeWskError(errors.New(errStr), EXITCODE_ERR_GENERAL, DISPLAY_MSG, NO_DISPLAY_USAGE)
return nil, werr
}
u.RawQuery = qs.Encode()
Debug(DbgInfo, "Returning route options '%s' from input struct %+v\n", u.String(), options)
return u, nil
}
开发者ID:RSulzmann,项目名称:openwhisk,代码行数:31,代码来源:util.go
示例7: getPage
func (it *Iter) getPage() error {
form, err := query.Values(it.params)
if err != nil {
return err
}
var listRes listResponse
_, err = it.client.execute(it.route, it.vars, &form, &listRes)
if err != nil {
return err
}
it.hasMore = listRes.HasMore
if it.params.After != "" {
it.params.After = listRes.Cursor
} else {
it.params.Before = listRes.Cursor
}
// Create a pointer to a slice value and set it to the slice
// MakeSlice allocates a value on the stack that is not addressable
dataPtr := reflect.New(it.valuesType)
dataPtr.Elem().Set(reflect.MakeSlice(it.valuesType, 0, 0))
if err := json.Unmarshal(listRes.Data, dataPtr.Interface()); err != nil {
return err
}
it.values = dataPtr.Elem()
return nil
}
开发者ID:metcalf,项目名称:saypi,代码行数:32,代码来源:iter.go
示例8: Find
func (repo CloudControllerRouteRepository) Find(host string, domain models.DomainFields, path string, port int) (models.Route, error) {
var route models.Route
queryString := queryStringForRouteSearch(host, domain.GUID, path, port)
q := struct {
Query string `url:"q"`
InlineRelationsDepth int `url:"inline-relations-depth"`
}{queryString, 1}
opt, _ := query.Values(q)
found := false
apiErr := repo.gateway.ListPaginatedResources(
repo.config.APIEndpoint(),
fmt.Sprintf("/v2/routes?%s", opt.Encode()),
resources.RouteResource{},
func(resource interface{}) bool {
keepSearching := true
route = resource.(resources.RouteResource).ToModel()
if doesNotMatchVersionSpecificAttributes(route, path, port) {
return keepSearching
}
found = true
return !keepSearching
})
if apiErr == nil && !found {
apiErr = errors.NewModelNotFoundError("Route", host)
}
return route, apiErr
}
开发者ID:yingkitw,项目名称:cli,代码行数:33,代码来源:routes.go
示例9: addOptions
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
origURL, err := url.Parse(s)
if err != nil {
return s, err
}
origValues := origURL.Query()
newValues, err := query.Values(opt)
if err != nil {
return s, err
}
for k, v := range newValues {
origValues[k] = v
}
origURL.RawQuery = origValues.Encode()
return origURL.String(), nil
}
开发者ID:MerlinDMC,项目名称:machine,代码行数:26,代码来源:godo.go
示例10: resource
func (c *Client) resource(path string, params interface{}) url.URL {
bp := map[string][]string{
"v": []string{CLIENT_VERSION},
}
if len(c.accessToken) > 0 {
bp["oauth_token"] = []string{c.accessToken}
} else {
bp["client_id"] = []string{c.clientId}
bp["client_secret"] = []string{c.clientSecret}
}
// TODO(dolapo): location params..
u := url.URL{
Scheme: "https",
Host: BASE_API_URL,
Path: "/v2/" + path,
RawQuery: url.Values(bp).Encode(),
}
if params != nil {
q, _ := query.Values(params)
u.RawQuery += "&" + q.Encode()
}
return u
}
开发者ID:heatxsink,项目名称:go-foursquare,代码行数:27,代码来源:foursquare.go
示例11: Submit
func (r *RedditClient) Submit(kind, title, text, subreddit string) {
log.Print(`Submitting...`)
bodyContent := SubmitRequest{
Kind: kind,
Title: title,
Text: text,
SR: subreddit,
Resubmit: true,
}
v, _ := query.Values(bodyContent)
bodyBuffer := bytes.NewBufferString(v.Encode())
request, err := http.NewRequest("POST", "https://oauth.reddit.com/api/submit", bodyBuffer)
if err != nil {
log.Fatal(err)
}
request.Header.Set(`Content-type`, `application/x-www-form-urlencoded`)
log.Print(request)
response, err := r.DoAuthorized(request)
if err != nil {
log.Fatal(err)
}
log.Print(response)
defer response.Body.Close()
bodyBytes, _ := ioutil.ReadAll(response.Body)
log.Print(string(bodyBytes))
}
开发者ID:warmans,项目名称:berlinbot,代码行数:31,代码来源:reddit.go
示例12: Events
// Events retrieves events for the currently authenticated user.
//
// See: https://developers.box.com/docs/#events-get-events-for-a-user
func (e *EventService) Events(options EventQueryOptions) (*http.Response, *EventCollection, error) {
queryString, err := query.Values(options)
if err != nil {
return nil, nil, err
}
req, err := e.NewRequest(
"GET",
"/events?"+queryString.Encode(),
nil,
)
if err != nil {
return nil, nil, err
}
var data EventCollection
resp, err := e.Do(req, &data)
if err != nil {
return resp, nil, err
}
for _, eve := range data.Entries {
if eve.Source == nil {
continue
}
if err = finishParsing(eve); err != nil {
return resp, nil, err
}
}
return resp, &data, err
}
开发者ID:superuser123,项目名称:box,代码行数:32,代码来源:events.go
示例13: NewRequest
// NewRequest creates an API request. A relative URL path can be provided in
// urlStr, in which case it is resolved relative to the base URL of the Client.
// Relative URL paths should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) NewRequest(method, path string, opt interface{}) (*http.Request, error) {
u := *c.baseURL
// Set the encoded opaque data
u.Opaque = c.baseURL.Path + path
q, err := query.Values(opt)
if err != nil {
return nil, err
}
u.RawQuery = q.Encode()
req := &http.Request{
Method: method,
URL: &u,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Host: u.Host,
}
req.Header.Set("Accept", "application/json")
req.Header.Set("PRIVATE-TOKEN", c.token)
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return req, nil
}
开发者ID:760379,项目名称:go-gitlab,代码行数:34,代码来源:gitlab.go
示例14: encodeBodyForm
// encodeBodyForm url encodes the value pointed to by bodyForm into an
// io.Reader, typically for use as a Request Body.
func encodeBodyForm(bodyForm interface{}) (io.Reader, error) {
values, err := goquery.Values(bodyForm)
if err != nil {
return nil, err
}
return strings.NewReader(values.Encode()), nil
}
开发者ID:andyjeffries,项目名称:sling,代码行数:9,代码来源:sling.go
示例15: ToQueryString
// Convert an interface{} to a urlencoded querystring
func ToQueryString(q interface{}) (string, error) {
v, err := query.Values(q)
if err != nil {
return "", err
}
return v.Encode(), nil
}
开发者ID:ChihChaoChang,项目名称:raintank-apps,代码行数:8,代码来源:client.go
示例16: WithQueryObject
// WithQueryObject adds multiple query parameters to request URL.
//
// object is converted to query string using github.com/google/go-querystring
// if it's a struct or pointer to struct, or github.com/ajg/form otherwise.
//
// Various object types are supported. Structs may contain "url" struct tag,
// similar to "json" struct tag for json.Marshal().
//
// Example:
// type MyURL struct {
// A int `url:"a"`
// B string `url:"b"`
// }
//
// req := NewRequest(config, "PUT", "http://example.com/path")
// req.WithQueryObject(MyURL{A: 123, B: "foo"})
// // URL is now http://example.com/path?a=123&b=foo
//
// req := NewRequest(config, "PUT", "http://example.com/path")
// req.WithQueryObject(map[string]interface{}{"a": 123, "b": "foo"})
// // URL is now http://example.com/path?a=123&b=foo
func (r *Request) WithQueryObject(object interface{}) *Request {
if object == nil {
return r
}
var (
q url.Values
err error
)
if reflect.Indirect(reflect.ValueOf(object)).Kind() == reflect.Struct {
q, err = query.Values(object)
if err != nil {
r.chain.fail(err.Error())
return r
}
} else {
q, err = form.EncodeToValues(object)
if err != nil {
r.chain.fail(err.Error())
return r
}
}
if r.query == nil {
r.query = make(url.Values)
}
for k, v := range q {
r.query[k] = append(r.query[k], v...)
}
return r
}
开发者ID:stellar,项目名称:bridge-server,代码行数:50,代码来源:request.go
示例17: NewRequest
// NewRequest creates an API request
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
buf := new(bytes.Buffer)
params := ""
if body != nil {
if method == "GET" {
v, err := query.Values(body)
if err != nil {
return nil, err
}
params = "?" + v.Encode()
} else {
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
}
req, err := http.NewRequest(method, u.String()+params, buf)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.SetBasicAuth(c.authID, c.authToken)
return req, nil
}
开发者ID:klyachin,项目名称:go-plivo,代码行数:36,代码来源:plivo.go
示例18: buildURLStruct
func buildURLStruct(userURL string, URLStruct interface{}) (string, error) {
parsedURL, err := url.Parse(userURL)
if err != nil {
return "", err
}
parsedQuery, err := url.ParseQuery(parsedURL.RawQuery)
if err != nil {
return "", err
}
queryStruct, err := query.Values(URLStruct)
if err != nil {
return "", err
}
for key, value := range queryStruct {
for _, v := range value {
parsedQuery.Add(key, v)
}
}
return addQueryParams(parsedURL, parsedQuery), nil
}
开发者ID:wakwanza,项目名称:grequests,代码行数:26,代码来源:request.go
示例19: GetMessaegByChat
func (chatter *Chatter) GetMessaegByChat() (result ChatMessages, err error) {
msg := ChatMessages{}
if len(chatter.UserMetas.Objects) < 1 {
return msg, errors.New("UserMetas is not ready")
}
req := GetMessageByChat{
ChatId: chatter.ChatId,
Count: 40,
UserToken: chatter.UserMetas.Objects[0].UserToken,
PopulateCreator: true,
}
params, _ := query.Values(req)
data := chatter.ApiCall("GET", "get-messages-by-chat", params.Encode())
if data != nil {
jsonErr := json.Unmarshal(data, &msg)
if jsonErr == nil {
for i, m := range msg.Messages {
date, parseError := time.Parse(time.RFC3339, m.CreatedDateStr)
if parseError != nil {
fmt.Printf("time parse error:%+v\n for %+v\n", parseError, m.CreatedDateStr)
} else {
msg.Messages[i].CreatedDate = date
}
}
// sort message by time ascending
// FIXME: or just revert the order if it's sorted!?
sort.Sort(msg.Messages)
return msg, nil
}
return msg, jsonErr
}
return msg, errors.New("Cant get chat message")
}
开发者ID:nitpicker,项目名称:livehouse_xmpp_muc_bridge,代码行数:33,代码来源:testlib.go
示例20: Listing
// Listing returns a slice of Submission pointers.
// See https://www.reddit.com/dev/api#listings for documentation.
func (a *AppOnlyOAuthSession) Listing(username, listing string, sort popularitySort, params ListingOptions) ([]*Submission, error) {
p, err := query.Values(params)
if err != nil {
return nil, err
}
if sort != "" {
p.Set("sort", string(sort))
}
type resp struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := &resp{}
url := fmt.Sprintf("https://oauth.reddit.com/user/%s/%s?%s", username, listing, p.Encode())
err = a.getBody(url, r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
}
开发者ID:imheresamir,项目名称:geddit,代码行数:32,代码来源:apponlyoauth_session.go
注:本文中的github.com/google/go-querystring/query.Values函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论