Exemplo n.º 1
0
func constructQueryString(data interface{}) (string, error) {
	v, err := query.Values(data)
	if err != nil {
		return "", nil
	}
	return v.Encode(), nil
}
Exemplo n.º 2
0
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
}
Exemplo n.º 3
0
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)
	}
}
Exemplo n.º 4
0
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()))
}
Exemplo n.º 5
0
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
}
Exemplo n.º 6
0
// 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
}
Exemplo n.º 7
0
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
}
Exemplo n.º 8
0
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
}
Exemplo n.º 9
0
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
}
Exemplo n.º 10
0
func FetchChannelsByQuery(accountId int64, q *request.Query, token string) ([]*models.Channel, error) {
	v, err := query.Values(q)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("/account/%d/channels?%s", accountId, v.Encode())
	res, err := sendRequestWithAuth("GET", url, nil, token)
	if err != nil {
		return nil, err
	}

	var ccs []*models.ChannelContainer
	err = json.Unmarshal(res, &ccs)
	if err != nil {
		return nil, err
	}

	channels := make([]*models.Channel, len(ccs))
	for i, cc := range ccs {
		channels[i] = cc.Channel
	}

	return channels, nil
}
Exemplo n.º 11
0
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
}
Exemplo n.º 12
0
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))
}
Exemplo n.º 13
0
// 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
}
Exemplo n.º 14
0
// 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
}
Exemplo n.º 15
0
// 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
}
Exemplo n.º 16
0
// 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
}
Exemplo n.º 17
0
// 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
}
Exemplo n.º 18
0
// 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
}
Exemplo n.º 19
0
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
}
Exemplo n.º 20
0
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")
}
Exemplo n.º 21
0
// 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
}
Exemplo n.º 22
0
// GetMaintenanceWindow gets an existing maintenance window.
func (c *Client) GetMaintenanceWindow(id string, o GetMaintenanceWindowOptions) (*MaintenanceWindow, error) {
	v, err := query.Values(o)
	if err != nil {
		return nil, err
	}
	resp, err := c.get("/mainteance_windows/" + id + "?" + v.Encode())
	return getMaintenanceWindowFromResponse(c, resp, err)
}
Exemplo n.º 23
0
// GetEscalationPolicy gets information about an existing escalation policy and its rules.
func (c *Client) GetEscalationPolicy(id string, o *GetEscalationPolicyOptions) (*EscalationPolicy, error) {
	v, err := query.Values(o)
	if err != nil {
		return nil, err
	}
	resp, err := c.get(escPath + "/" + id + "?" + v.Encode())
	return getEscalationPolicyFromResponse(c, resp, err)
}
Exemplo n.º 24
0
// GetUser gets details about an existing user.
func (c *Client) GetUser(id string, o GetUserOptions) (*User, error) {
	v, err := query.Values(o)
	if err != nil {
		return nil, err
	}
	resp, err := c.get("/users/" + id + "?" + v.Encode())
	return getUserFromResponse(c, resp, err)
}
Exemplo n.º 25
0
// GetIntegration gets details about an integration belonging to a service.
func (c *Client) GetIntegration(serviceID, integrationID string, o GetIntegrationOptions) (*Integration, error) {
	v, queryErr := query.Values(o)
	if queryErr != nil {
		return nil, queryErr
	}
	resp, err := c.get("/services/" + serviceID + "/integrations/" + integrationID + "?" + v.Encode())
	return getIntegrationFromResponse(c, resp, err)
}
Exemplo n.º 26
0
func (r *Router) URLToRepoSearch(repoPath string, at vcs.CommitID, opt vcs.SearchOptions) *url.URL {
	u := r.URLTo(RouteRepoSearch, "RepoPath", repoPath, "CommitID", string(at))
	q, err := query.Values(opt)
	if err != nil {
		panic(err.Error())
	}
	u.RawQuery = q.Encode()
	return u
}
Exemplo n.º 27
0
func (r *Router) URLToRepoCommitters(repoPath string, opt vcs.CommittersOptions) *url.URL {
	u := r.URLTo(RouteRepoCommitters, "RepoPath", repoPath)
	q, err := query.Values(opt)
	if err != nil {
		panic(err.Error())
	}
	u.RawQuery = q.Encode()
	return u
}
Exemplo n.º 28
0
// buildGetRequest is an internal method to prepare a "GET" request that will send to OpsGenie.
func (cli *OpsGenieClient) buildGetRequest(uri string, request interface{}) goreq.Request {
	req := cli.buildCommonRequestProps()
	req.Method = "GET"
	req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"
	uri = cli.OpsGenieAPIUrl() + uri
	v, _ := goquery.Values(request)
	req.Uri = uri + "?" + v.Encode()
	logging.Logger().Info("Executing OpsGenie request to ["+uri+"] with parameters: ", v)
	return req
}
Exemplo n.º 29
0
// getQueryOpts converts RequestOptions to url.Values.
func getQueryOpts(opts *RequestOptions) (url.Values, error) {
	if opts != nil {
		values, err := query.Values(opts)
		if err != nil {
			return nil, err
		}
		return values, nil
	}
	return nil, nil
}
Exemplo n.º 30
0
Arquivo: vk.go Projeto: Alezhka/vk
// Request generate new request with provided method and arguments
func (f Factory) Request(method string, arguments interface{}) (request Request) {
	request.Token = f.Token
	request.Method = method
	if arguments != nil {
		var err error
		request.Values, err = query.Values(arguments)
		must(err)
	}
	return request
}