Beispiel #1
2
/*
Build URL for an API method call. Note that when using GET, we will also append query parameter to URL
*/
func (api *Api) buildUrl(method string, option map[string]string) string {
	q := url.Values{}
	for k, v := range option {
		q.Add(k, v)
	}
	return api.config.Endpoint(method) + "?" + q.Encode()
}
Beispiel #2
2
func copyValues(dst, src url.Values) {
	for k, vs := range src {
		for _, value := range vs {
			dst.Add(k, value)
		}
	}
}
Beispiel #3
1
// GetBookmarkCounts call hatena bookmark count api.
func GetBookmarkCounts(urls []string) (map[string]int, error) {
	query := neturl.Values{}
	for _, url := range urls {
		u, err := neturl.Parse(url)
		if err != nil {
			return map[string]int{}, err
		}
		query.Add("url", u.String())
	}

	req, _ := neturl.Parse(EntryCountsAPIURL)
	req.RawQuery = query.Encode()

	res, err := http.Get(req.String())
	if err != nil {
		return map[string]int{}, err
	}

	body, _ := ioutil.ReadAll(res.Body)
	defer res.Body.Close()

	counts := map[string]int{}
	json.Unmarshal(body, &counts)
	return counts, nil
}
Beispiel #4
1
func (h *ZJUJudger) Login(_ UserInterface) error {

	h.client.Get("http://acm.zju.edu.cn/onlinejudge/login.do")

	uv := url.Values{}
	uv.Add("handle", h.username)
	uv.Add("password", h.userpass)

	req, err := http.NewRequest("POST", "http://acm.zju.edu.cn/onlinejudge/login.do", strings.NewReader(uv.Encode()))
	if err != nil {
		return BadInternet
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := h.client.Do(req)
	if err != nil {
		log.Println("err", err)
		return BadInternet
	}
	defer resp.Body.Close()

	b, _ := ioutil.ReadAll(resp.Body)
	html := string(b)

	if strings.Index(html, "Handle or password is invalid.") >= 0 ||
		strings.Index(html, "Handle is required.") >= 0 ||
		strings.Index(html, "Password is required.") >= 0 {
		return LoginFailed
	}

	return nil
}
Beispiel #5
0
// URL returns the current working URL.
func (r *Request) URL() *url.URL {
	p := r.pathPrefix
	if r.namespaceSet && len(r.namespace) > 0 {
		p = path.Join(p, "namespaces", r.namespace)
	}
	if len(r.resource) != 0 {
		p = path.Join(p, strings.ToLower(r.resource))
	}
	// Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compat if nothing was changed
	if len(r.resourceName) != 0 || len(r.subpath) != 0 || len(r.subresource) != 0 {
		p = path.Join(p, r.resourceName, r.subresource, r.subpath)
	}

	finalURL := &url.URL{}
	if r.baseURL != nil {
		*finalURL = *r.baseURL
	}
	finalURL.Path = p

	query := url.Values{}
	for key, values := range r.params {
		for _, value := range values {
			query.Add(key, value)
		}
	}

	// timeout is handled specially here.
	if r.timeout != 0 {
		query.Set("timeout", r.timeout.String())
	}
	finalURL.RawQuery = query.Encode()
	return finalURL
}
Beispiel #6
0
func GetMessages(secret, deviceid string) (mr *MessagesResponse, err error) {
	pform := url.Values{}
	pform.Add("secret", secret)
	pform.Add("device_id", deviceid)
	// fmt.Printf("Requesting messages with %s\n", pform.Encode())
	resp, err := http.Get("https://api.pushover.net/1/messages.json?" + pform.Encode())
	if err != nil {
		return
	}
	if resp.StatusCode == 200 {
		var jbuf []byte
		jbuf, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Failed to read from body: %s", err)
			return
		}
		mr = &MessagesResponse{}
		jerr := json.Unmarshal(jbuf, mr)
		if jerr != nil {
			fmt.Printf("Bad unmarshal: [%s]\n", jerr)
			return
		}
		// fmt.Printf("M is %d %t %+v\n", mr.APIResponse.Status, mr.User.DesktopLicense, *mr)
	} else {
		b, _ := ioutil.ReadAll(resp.Body)
		err = fmt.Errorf("Bad Messages response from pushover: %s\n%s", resp.Status, b)
	}
	return
}
Beispiel #7
0
func (c *Client) buildBody(params map[string]string) url.Values {
	body := url.Values{}
	for k := range params {
		body.Add(k, params[k])
	}
	return body
}
Beispiel #8
0
// Subscribes a customer to a new plan.
//
// see https://stripe.com/docs/api#update_subscription
func (self *SubscriptionClient) Update(customerId string, params *SubscriptionParams) (*Subscription, error) {
	values := url.Values{"plan": {params.Plan}}

	// set optional parameters
	if len(params.Coupon) != 0 {
		values.Add("coupon", params.Coupon)
	}
	if params.Prorate {
		values.Add("prorate", "true")
	}
	if params.TrialEnd != 0 {
		values.Add("trial_end", strconv.FormatInt(params.TrialEnd, 10))
	}
	if params.Quantity != 0 {
		values.Add("quantity", strconv.FormatInt(params.Quantity, 10))
	}
	// attach a new card, if requested
	if len(params.Token) != 0 {
		values.Add("card", params.Token)
	} else if params.Card != nil {
		appendCardParamsToValues(params.Card, &values)
	}

	s := Subscription{}
	path := "/v1/customers/" + url.QueryEscape(customerId) + "/subscription"
	err := query("POST", path, values, &s)
	return &s, err
}
Beispiel #9
0
func (r *RestService) Get(urlPath string, params map[string]string) ([]byte, int, error) {
	loc, _ := url.Parse(r.endpoint)
	loc.Path = urlPath

	values := url.Values{}
	for k, v := range params {
		values.Add(k, v)
	}
	loc.RawQuery = values.Encode()

	if os.Getenv("KDEPLOY_DRYRUN") == "1" {
		log.Infof("Get request url: %s", loc.String())
		return nil, 200, nil
	} else {
		log.Debugf("Get request url: %s", loc.String())
	}

	response, err := r.client.Get(loc.String())
	if err != nil {
		return nil, -1, err
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		return nil, response.StatusCode, fmt.Errorf("unexpected http error code: %v (%s)", response.StatusCode, http.StatusText(response.StatusCode))
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, -1, err
	}

	return body, response.StatusCode, nil
}
func (s *Server) DeleteTask(name string) error {
	v := url.Values{}
	v.Add("name", name)
	req, err := http.NewRequest("DELETE", s.URL()+"/task?"+v.Encode(), nil)
	if err != nil {
		return err
	}
	client := &http.Client{}
	r, err := client.Do(req)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	if r.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status code got %d exp %d", r.StatusCode, http.StatusOK)
	}
	// Decode valid response
	type resp struct {
		Error string `json:"Error"`
	}
	d := json.NewDecoder(r.Body)
	rp := resp{}
	d.Decode(&rp)
	if rp.Error != "" {
		return errors.New(rp.Error)
	}
	return nil
}
Beispiel #11
0
func handleConnectRequest(form *url.Values, body interface{}) {
	_, isConduitConnect := body.(*requests.ConduitConnectRequest)

	if isConduitConnect {
		form.Add("__conduit__", "true")
	}
}
Beispiel #12
0
func (s *MailGunServer) Send(message Message) int {
	if Debug {
		InfoLog.Printf("sending email from %s to %s with subject %s via MailGun.\n", message.From, message.To, message.Subject)
	}

	data := url.Values{}
	data.Set("from", message.From)
	for _, to := range message.To {
		data.Add("to", to)
	}
	data.Set("subject", message.Subject)
	data.Set("text", message.Text)

	r, err := http.NewRequest("POST", s.Server.Url+"messages", bytes.NewBufferString(data.Encode()))
	check(err)
	r.SetBasicAuth("api", mailGunKey)
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

	if Debug {
		InfoLog.Println("Sending Request " + r.URL.String())
	}
	res, err := http.DefaultClient.Do(r)
	if err != nil {
		ErrorLog.Println("Error sending mail via MailGun", err)
		return 500
	}

	if Debug {
		InfoLog.Println("Received: " + res.Status)
	}
	return res.StatusCode
}
Beispiel #13
0
func (p *OauthProxy) redeemCode(code string) (string, error) {
	if code == "" {
		return "", errors.New("missing code")
	}
	params := url.Values{}
	params.Add("redirect_uri", p.redirectUrl.String())
	params.Add("client_id", p.clientID)
	params.Add("client_secret", p.clientSecret)
	params.Add("code", code)
	params.Add("grant_type", "authorization_code")
	log.Printf("body is %s", params.Encode())
	req, err := http.NewRequest("POST", p.oauthRedemptionUrl.String(), bytes.NewBufferString(params.Encode()))
	if err != nil {
		log.Printf("failed building request %s", err.Error())
		return "", err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	json, err := apiRequest(req)
	if err != nil {
		log.Printf("failed making request %s", err.Error())
		return "", err
	}
	access_token, err := json.Get("access_token").String()
	if err != nil {
		return "", err
	}
	return access_token, nil
}
Beispiel #14
0
func (h *httpApplicator) GetMatches(selector labels.Selector, labelType Type) ([]Labeled, error) {
	params := url.Values{}
	params.Add("selector", selector.String())
	params.Add("type", labelType.String())

	// Make value copy of URL; don't want to mutate the URL in the struct.
	urlToGet := *h.matchesEndpoint
	urlToGet.RawQuery = params.Encode()

	resp, err := h.client.Get(urlToGet.String())
	if err != nil {
		return []Labeled{}, err
	}

	defer resp.Body.Close()

	matches := []string{}
	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&matches)
	if err != nil {
		return []Labeled{}, err
	}

	labeled := make([]Labeled, len(matches))

	for i, s := range matches {
		labeled[i] = Labeled{
			ID:        s,
			LabelType: labelType,
			Labels:    labels.Set{},
		}
	}

	return labeled, nil
}
Beispiel #15
0
func emtRequest(path string, req_values url.Values) string {
	creds := readCredentials(cred_file)
	api_url := "https://openbus.emtmadrid.es:9443/emt-proxy-server/last/" + path
	req_values.Add("idClient", creds.ClientID)
	req_values.Add("passKey", creds.Password)

	req, err := http.NewRequest("POST", api_url,
		bytes.NewBufferString(req_values.Encode()))
	req.Header.Set("X-Custom-Header", "busdm")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	client := &http.Client{Transport: tr}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	fmt.Println("response Headers:", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))
	return string(body)
}
Beispiel #16
0
func New(userId, password string) (ada *Adapter, status int, errMsg error) {
	ada = new(Adapter)
	ada.WithJar()
	status = http.StatusOK

	form := url.Values{}
	form.Add("i_user", userId)
	form.Add("i_pass", password)

	resp, err := ada.PostForm(AuthURL, form)
	if err != nil {
		return nil, http.StatusBadGateway, fmt.Errorf("Failed to post login form to %s: %s", AuthURL, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		errMsg = fmt.Errorf("Server replied %s.", http.StatusText(resp.StatusCode))
	} else if url := resp.Request.URL; url.Host != "learn.cic.tsinghua.edu.cn" {
		errMsg = fmt.Errorf("Stopped at incorrect URL: %s.", url.String())
	}
	if errMsg != nil {
		return nil, http.StatusUnauthorized, fmt.Errorf("Failed to login to %s: %s", AuthURL, errMsg)
	}

	return
}
func GenerateAmazonUrl(api AmazonProductAPI, Operation string, Parameters map[string]string) (finalUrl *url.URL, err error) {

	result, err := url.Parse(api.Host)
	if err != nil {
		return nil, err
	}

	result.Host = api.Host
	result.Scheme = "https"
	result.Path = "/onca/xml"

	values := url.Values{}
	values.Add("Operation", Operation)
	values.Add("Service", "AWSECommerceService")
	values.Add("AWSAccessKeyId", api.AccessKey)
	values.Add("Version", "2013-08-01")
	values.Add("AssociateTag", api.AssociateTag)

	for k, v := range Parameters {
		values.Set(k, v)
	}

	params := values.Encode()
	result.RawQuery = params

	return result, nil
}
func (b TelegramBot) sendData(id int64, data string, options SendMessageOptions, dataKey string, target string) (string, error) {
	v := url.Values{}
	v.Add("chat_id", asString(id))
	v.Add(dataKey, data)

	return b.finalizeRequest(target, v)
}
Beispiel #19
0
func (api *Client) _search(path, query string, params SearchParameters, files, messages bool) (response *searchResponseFull, error error) {
	values := url.Values{
		"token": {api.config.token},
		"query": {query},
	}
	if params.Sort != DEFAULT_SEARCH_SORT {
		values.Add("sort", params.Sort)
	}
	if params.SortDirection != DEFAULT_SEARCH_SORT_DIR {
		values.Add("sort_dir", params.SortDirection)
	}
	if params.Highlight != DEFAULT_SEARCH_HIGHLIGHT {
		values.Add("highlight", strconv.Itoa(1))
	}
	if params.Count != DEFAULT_SEARCH_COUNT {
		values.Add("count", strconv.Itoa(params.Count))
	}
	if params.Page != DEFAULT_SEARCH_PAGE {
		values.Add("page", strconv.Itoa(params.Page))
	}
	response = &searchResponseFull{}
	err := post(path, values, response, api.debug)
	if err != nil {
		return nil, err
	}
	if !response.Ok {
		return nil, errors.New(response.Error)
	}
	return response, nil

}
Beispiel #20
0
// RecentMedia gets recent media from a geography subscription that created by
// real-time subscriptions.
//
// Instagram API docs: http://instagram.com/developer/endpoints/geographies/#get_geographies_media_recent
func (s *GeographiesService) RecentMedia(geoId string, opt *Parameters) ([]Media, *ResponsePagination, error) {
	u := fmt.Sprintf("geographies/%v/media/recent", geoId)
	if opt != nil {
		params := url.Values{}
		if opt.MinID != "" {
			params.Add("min_id", opt.MinID)
		}
		if opt.Count != 0 {
			params.Add("count", strconv.FormatUint(opt.Count, 10))
		}
		u += "?" + params.Encode()
	}

	req, err := s.client.NewRequest("GET", u, "")
	if err != nil {
		return nil, nil, err
	}

	media := new([]Media)
	_, err = s.client.Do(req, media)
	if err != nil {
		return nil, nil, err
	}

	page := new(ResponsePagination)
	if s.client.Response.Pagination != nil {
		page = s.client.Response.Pagination
	}

	return *media, page, err
}
Beispiel #21
0
func (t Twilio) sendSMS(body map[string]interface{}, id baton.CommandID) {
	to := body["to"].(string)
	from := body["from"].(string)
	form := url.Values{"To": {to}, "From": {from}}

	if message, ok := body["body"]; ok {
		form.Add("Body", message.(string))
	}
	if url, ok := body["url"]; ok {
		form.Add("MediaUrl", url.(string))
	}

	res, err := t.postForm(fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", t.UserId), form)
	if err != nil {
		log.WithField("error", err).Error("Error in POST to /Messages.json")
		return
	}
	defer res.Body.Close()

	var jsonResponse map[string]interface{}
	if err := json.NewDecoder(res.Body).Decode(&jsonResponse); err != nil {
		log.WithField("error", err).Error("Error decoding body as JSON")
		return
	}
	delete(jsonResponse, "account_sid")
	send(id, "send-sms", jsonResponse)
}
Beispiel #22
0
// SendLocation sends a location to a chat.
//
// Requires ChatID, Latitude, and Longitude.
// ReplyToMessageID and ReplyMarkup are optional.
func (bot *BotAPI) SendLocation(config LocationConfig) (Message, error) {
	v := url.Values{}
	v.Add("chat_id", strconv.Itoa(config.ChatID))
	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
	if config.ReplyToMessageID != 0 {
		v.Add("reply_to_message_id", strconv.Itoa(config.ReplyToMessageID))
	}
	if config.ReplyMarkup != nil {
		data, err := json.Marshal(config.ReplyMarkup)
		if err != nil {
			return Message{}, err
		}

		v.Add("reply_markup", string(data))
	}

	resp, err := bot.MakeRequest("sendLocation", v)
	if err != nil {
		return Message{}, err
	}

	var message Message
	json.Unmarshal(resp.Result, &message)

	if bot.Debug {
		log.Printf("sendLocation req : %+v\n", v)
		log.Printf("sendLocation resp: %+v\n", message)
	}

	return message, nil
}
Beispiel #23
0
func (c Client) List(params *stripe.RecipientListParams) *Iter {
	type recipientList struct {
		stripe.ListMeta
		Values []*stripe.Recipient `json:"data"`
	}

	var body *url.Values
	var lp *stripe.ListParams
	var p *stripe.Params

	if params != nil {
		body = &url.Values{}

		if params.Verified {
			body.Add("verified", strconv.FormatBool(true))
		}

		params.AppendTo(body)
		lp = &params.ListParams
		p = params.ToParams()
	}

	return &Iter{stripe.GetIter(lp, body, func(b url.Values) ([]interface{}, stripe.ListMeta, error) {
		list := &recipientList{}
		err := c.B.Call("GET", "/recipients", c.Key, &b, p, list)

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}
Beispiel #24
0
// SetWebhook sets a webhook.
// If this is set, GetUpdates will not get any data!
//
// Requires Url OR to set Clear to true.
func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
	if config.Certificate == nil {
		v := url.Values{}
		if !config.Clear {
			v.Add("url", config.URL.String())
		}

		return bot.MakeRequest("setWebhook", v)
	}

	params := make(map[string]string)
	params["url"] = config.URL.String()

	resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
	if err != nil {
		return APIResponse{}, err
	}

	var apiResp APIResponse
	json.Unmarshal(resp.Result, &apiResp)

	if bot.Debug {
		log.Printf("setWebhook resp: %+v\n", apiResp)
	}

	return apiResp, nil
}
Beispiel #25
0
func (self *ReportClient) Request(path string, params map[string]string) (ret interface{}, err error) {
	args := make(map[string]string, len(params)+3)
	for k, v := range params {
		args[k] = v
	}

	args["api_key"] = self.apiKey
	args["expire"] = fmt.Sprintf("%d", time.Now().Unix()+600)
	args["sig"] = hashArgs(self.apiSecret, args)

	query := url.Values{}
	for k, v := range args {
		query.Add(k, v)
	}
	url := fmt.Sprintf("%s/%s/%s/?%s", ENDPOINT, VERSION, path, query.Encode())
	resp, urlerr := http.Get(url)
	if urlerr != nil {
		err = urlerr
		return
	}

	defer resp.Body.Close()
	body, httperr := ioutil.ReadAll(resp.Body)
	if httperr != nil {
		err = httperr
		return
	}
	jsonerr := json.Unmarshal(body, &ret)
	if jsonerr != nil {
		err = jsonerr
		return
	}
	return ret, nil
}
Beispiel #26
0
func (f *UrlEncodedPayload) GetPayloadBuffer() (*bytes.Buffer, error) {
	data := url.Values{}
	for _, keyVal := range f.Values {
		data.Add(keyVal.key, keyVal.value)
	}
	return bytes.NewBufferString(data.Encode()), nil
}
Beispiel #27
0
func Detect_language(q string) string {
	var Url *url.URL
	Url, err := url.Parse("https://www.googleapis.com")
	if err != nil {
		fmt.Println(err)
	}

	Url.Path += "/language/translate/v2/detect"
	parameters := url.Values{}
	parameters.Add("q", q)
	parameters.Add("key", Google_key())
	Url.RawQuery = parameters.Encode()

	resp, err := http.Get(Url.String())
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	var data gtresponse
	json.Unmarshal(body, &data)

	lang := data.Data.Detections[0][0].Language
	return lang
}
Beispiel #28
0
func (s OAuth2Service) GetToken() (AdminAuthToken, error) {
	opts := s.client.Options

	val := url.Values{}
	val.Add("grant_type", "client_credentials")
	req, err := http.NewRequest("POST", s.client.URL(authTokenURL), bytes.NewBufferString(val.Encode()))
	if err != nil {
		return AdminAuthToken{}, err
	}

	req.SetBasicAuth(opts.ClientID, opts.Secret)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Accept-Language", opts.AcceptLanguage)

	res, err := s.client.Do(req)
	if err != nil {
		return AdminAuthToken{}, err
	}
	defer res.Body.Close()

	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return AdminAuthToken{}, err
	}

	var token AdminAuthToken
	return token, json.Unmarshal(data, &token)
}
Beispiel #29
0
// GetGroupHistory retrieves message history for a give group
func (api *Slack) GetGroupHistory(groupId string, params HistoryParameters) (*History, error) {
	values := url.Values{
		"token":   {api.config.token},
		"channel": {groupId},
	}
	if params.Latest != DEFAULT_HISTORY_LATEST {
		values.Add("latest", params.Latest)
	}
	if params.Oldest != DEFAULT_HISTORY_OLDEST {
		values.Add("oldest", params.Oldest)
	}
	if params.Count != DEFAULT_HISTORY_COUNT {
		values.Add("count", strconv.Itoa(params.Count))
	}
	if params.Inclusive != DEFAULT_HISTORY_INCLUSIVE {
		if params.Inclusive {
			values.Add("inclusive", "1")
		} else {
			values.Add("inclusive", "0")
		}
	}
	response, err := groupRequest("groups.history", values, api.debug)
	if err != nil {
		return nil, err
	}
	return &response.History, nil
}
Beispiel #30
0
func (c Client) List(params *stripe.BitcoinTransactionListParams) *Iter {
	type receiverList struct {
		stripe.ListMeta
		Values []*stripe.BitcoinTransaction `json:"data"`
	}

	var body *url.Values
	var lp *stripe.ListParams
	var p *stripe.Params

	if params != nil {
		body = &url.Values{}

		if len(params.Customer) > 0 {
			body.Add("customer", params.Customer)
		}

		params.AppendTo(body)
		lp = &params.ListParams
		p = params.ToParams()
	}

	return &Iter{stripe.GetIter(lp, body, func(b url.Values) ([]interface{}, stripe.ListMeta, error) {
		list := &receiverList{}
		err := c.B.Call("GET", fmt.Sprintf("/bitcoin/receivers/%v/transactions", params.Receiver), c.Key, &b, p, list)

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}