Example #1
0
File: http.go Project: jsocol/nsq
func (s *httpServer) pauseChannelHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		log.Printf("ERROR: invalid %s to POST only method", req.Method)
		http.Error(w, "INVALID_REQUEST", 500)
		return
	}
	reqParams := &util.PostParams{req}

	topicName, channelName, err := util.GetTopicChannelArgs(reqParams)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	producers := s.getProducers(topicName)
	for _, addr := range producers {
		endpoint := fmt.Sprintf("http://%s%s?topic=%s&channel=%s",
			addr, req.URL.Path, url.QueryEscape(topicName), url.QueryEscape(channelName))
		log.Printf("NSQD: calling %s", endpoint)

		_, err := util.ApiRequest(endpoint)
		if err != nil {
			log.Printf("ERROR: nsqd %s - %s", endpoint, err.Error())
			continue
		}
	}

	s.notifyAdminAction(strings.TrimLeft(req.URL.Path, "/"), topicName, channelName, "", req)

	http.Redirect(w, req, fmt.Sprintf("/topic/%s/%s", url.QueryEscape(topicName), url.QueryEscape(channelName)), 302)
}
Example #2
0
// Encode encodes the values into ``URL encoded'' form
// ("acl&bar=baz&foo=quux") sorted by key.
func Encode(v url.Values) string {
	if v == nil {
		return ""
	}
	var buf bytes.Buffer
	keys := make([]string, 0, len(v))
	for k := range v {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		vs := v[k]
		prefix := url.QueryEscape(k)
		for _, v := range vs {
			if buf.Len() > 0 {
				buf.WriteByte('&')
			}
			buf.WriteString(prefix)
			if v != "" {
				buf.WriteString("=")
				buf.WriteString(url.QueryEscape(v))
			}
		}
	}
	return buf.String()
}
Example #3
0
func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) {
	var req *http.Request
	var err error
	switch c.authMethod {
	case AuthMethodClientSecretPost:
		values.Set("client_secret", c.creds.Secret)
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
	case AuthMethodClientSecretBasic:
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
		encodedID := url.QueryEscape(c.creds.ID)
		encodedSecret := url.QueryEscape(c.creds.Secret)
		req.SetBasicAuth(encodedID, encodedSecret)
	default:
		panic("misconfigured client: auth method not supported")
	}

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

}
Example #4
0
File: goa.go Project: alytvynov/goa
func (h handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if session.Store == nil {
		// server should not be started until Store is set!
		panic(session.ErrNoStore)
	}
	// login page should be allowed
	if req.URL.Path == LoginPage {
		h.Handler.ServeHTTP(rw, req)
		return
	}
	// check the cookie existance
	s, err := session.Store.Get(req)
	if err != nil {
		http.Redirect(rw, req, LoginPage+"?from="+url.QueryEscape(req.URL.String()), http.StatusFound)
		return
	}
	// check for cookie expiration
	if s.Expires.Before(time.Now()) {
		if err = session.Store.Del(req, rw); err != nil {
			http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		http.Redirect(rw, req, LoginPage+"?from="+url.QueryEscape(req.URL.String()), http.StatusTemporaryRedirect)
		return
	}
	// refresh expiration and store new cookie
	s.Expires = time.Now().Add(session.MaxAge)
	session.Store.Put(req, rw, *s)
	h.Handler.ServeHTTP(rw, req)
}
Example #5
0
func (r *registry) Push(job, instance, pushURL, method string) error {
	if !strings.Contains(pushURL, "://") {
		pushURL = "http://" + pushURL
	}
	pushURL = fmt.Sprintf("%s/metrics/jobs/%s", pushURL, url.QueryEscape(job))
	if instance != "" {
		pushURL += "/instances/" + url.QueryEscape(instance)
	}
	buf := r.getBuf()
	defer r.giveBuf(buf)
	if err := r.writePB(expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)); err != nil {
		if r.panicOnCollectError {
			panic(err)
		}
		return err
	}
	req, err := http.NewRequest(method, pushURL, buf)
	if err != nil {
		return err
	}
	req.Header.Set(contentTypeHeader, DelimitedTelemetryContentType)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 202 {
		return fmt.Errorf("unexpected status code %d while pushing to %s", resp.StatusCode, pushURL)
	}
	return nil
}
Example #6
0
// ListAllPreparer prepares the ListAll request.
func (client RecordSetsClient) ListAllPreparer(resourceGroupName string, zoneName string, top string, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": url.QueryEscape(resourceGroupName),
		"subscriptionId":    url.QueryEscape(client.SubscriptionID),
		"zoneName":          url.QueryEscape(zoneName),
	}

	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(top) > 0 {
		queryParameters["$top"] = top
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	return autorest.Prepare(&http.Request{},
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/recordsets"),
		autorest.WithPathParameters(pathParameters),
		autorest.WithQueryParameters(queryParameters))
}
Example #7
0
func (s *httpServer) pauseChannelHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		s.ctx.nsqadmin.logf("ERROR: invalid %s to POST only method", req.Method)
		http.Error(w, "INVALID_REQUEST", 500)
		return
	}
	reqParams := &http_api.PostParams{req}

	topicName, channelName, err := http_api.GetTopicChannelArgs(reqParams)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	verb := "pause"
	if strings.Contains(req.URL.Path, "unpause") {
		verb = "unpause"
	}

	producerAddrs := s.getProducers(topicName)
	s.performVersionNegotiatedRequestsToNSQD(
		s.ctx.nsqadmin.opts.NSQLookupdHTTPAddresses,
		producerAddrs,
		verb+"_channel",
		"channel/"+verb,
		fmt.Sprintf("topic=%s&channel=%s",
			url.QueryEscape(topicName), url.QueryEscape(channelName)))

	s.notifyAdminAction(verb+"_channel", topicName, channelName, "", req)

	http.Redirect(w, req, fmt.Sprintf("/topic/%s/%s", url.QueryEscape(topicName), url.QueryEscape(channelName)), 302)
}
Example #8
0
func emptyChannelHandler(w http.ResponseWriter, req *http.Request) {
	reqParams, err := util.NewReqParams(req)
	if err != nil {
		log.Printf("ERROR: failed to parse request params - %s", err.Error())
		http.Error(w, "INVALID_REQUEST", 500)
		return
	}

	topicName, channelName, err := util.GetTopicChannelArgs(reqParams)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	producers, _ := getLookupdTopicProducers(topicName, lookupdHTTPAddrs)
	for _, addr := range producers {
		endpoint := fmt.Sprintf("http://%s/empty_channel?topic=%s&channel=%s", addr, url.QueryEscape(topicName), url.QueryEscape(channelName))
		log.Printf("NSQD: calling %s", endpoint)

		_, err := nsq.ApiRequest(endpoint)
		if err != nil {
			log.Printf("ERROR: nsqd %s - %s", endpoint, err.Error())
			continue
		}
	}

	http.Redirect(w, req, fmt.Sprintf("/topic/%s", url.QueryEscape(topicName)), 302)
}
func (hm HMACMiddleware) parseFormParams(values url.Values) string {
	kvValues := map[string]string{}
	keys := []string{}

	log.Debug("Parsing header values")

	for k, v := range values {
		log.Debug("Form parser - processing key: ", k)
		log.Debug("Form parser - processing value: ", v)
		encodedKey := url.QueryEscape(k)
		encodedVals := []string{}
		for _, raw_value := range v {
			encodedVals = append(encodedVals, url.QueryEscape(raw_value))
		}
		joined_vals := strings.Join(encodedVals, "|")
		kvPair := encodedKey + "=" + joined_vals
		kvValues[k] = kvPair
		keys = append(keys, k)
	}

	// sort the keys in alphabetical order
	sort.Strings(keys)
	sortedKvs := []string{}

	// Put the prepared key value params in order according to above sort
	for _, sk := range keys {
		sortedKvs = append(sortedKvs, kvValues[sk])
	}

	// Join the kv's up as per spec
	prepared_params := strings.Join(sortedKvs, "&")

	return prepared_params
}
Example #10
0
// Search for available phone numbers in a given country, filtering by a pattern
func (c *Numbers) SearchAvailableWithOptions(countryCode string, opts NumberSearchOptions) (response NumberSearchResponse, err error) {
	if len(countryCode) <= 0 {
		err = errors.New("Invalid country code field specified")
		return
	}

	client := &http.Client{}

	requestUrl := apiRoot + "/number/search/" + c.client.apiKey + "/" + c.client.apiSecret + "/" + countryCode
	if opts.Pattern != "" && opts.SearchPattern != "" {
		requestUrl += "?pattern=" + url.QueryEscape(opts.Pattern)
		if opts.SearchPattern != "" {
			requestUrl += "&search_pattern=" + url.QueryEscape(opts.SearchPattern)
		}
	}

	r, _ := http.NewRequest("GET", requestUrl, nil)
	r.Header.Add("Accept", "application/json")

	resp, err := client.Do(r)
	defer resp.Body.Close()

	if err != nil {
		return
	}

	body, _ := ioutil.ReadAll(resp.Body)

	err = json.Unmarshal(body, &response)
	return

}
Example #11
0
func appendParam(req *http.Request, k, v string) {
	sep := ""
	if req.URL.RawQuery != "" {
		sep = "&"
	}
	req.URL.RawQuery += sep + url.QueryEscape(k) + "=" + url.QueryEscape(v)
}
Example #12
0
// ListJobHistoryPreparer prepares the ListJobHistory request.
func (client JobsClient) ListJobHistoryPreparer(resourceGroupName string, jobCollectionName string, jobName string, top *int, skip *int, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"jobCollectionName": url.QueryEscape(jobCollectionName),
		"jobName":           url.QueryEscape(jobName),
		"resourceGroupName": url.QueryEscape(resourceGroupName),
		"subscriptionId":    url.QueryEscape(client.SubscriptionID),
	}

	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if top != nil {
		queryParameters["$top"] = top
	}
	if skip != nil {
		queryParameters["$skip"] = skip
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	return autorest.Prepare(&http.Request{},
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}/history"),
		autorest.WithPathParameters(pathParameters),
		autorest.WithQueryParameters(queryParameters))
}
Example #13
0
// Configure sets the database connection values
func (writer *influxDBWriter10) configure(conf core.PluginConfig, prod *InfluxDB) error {
	writer.host = conf.GetString("Host", "localhost:8086")
	writer.username = conf.GetString("User", "")
	writer.password = conf.GetString("Password", "")
	writer.databaseTemplate = conf.GetString("Database", "default")
	writer.buffer = shared.NewByteStream(4096)
	writer.connectionUp = false
	writer.timeBasedDBName = conf.GetBool("TimeBasedName", true)
	writer.Control = prod.Control

	writer.writeURL = fmt.Sprintf("http://%s/write", writer.host)
	writer.queryURL = fmt.Sprintf("http://%s/query", writer.host)
	writer.pingURL = fmt.Sprintf("http://%s/ping", writer.host)
	writer.separator = '?'

	if writer.username != "" {
		credentials := fmt.Sprintf("?u=%s&p=%s", url.QueryEscape(writer.username), url.QueryEscape(writer.password))
		writer.writeURL += credentials
		writer.queryURL += credentials
		writer.separator = '&'
	}

	writer.writeURL = fmt.Sprintf("%s%cprecision=ms", writer.writeURL, writer.separator)
	prod.SetCheckFuseCallback(writer.isConnectionUp)
	return nil
}
Example #14
0
func Permissions(permissionName string) martini.Handler {
	return func(token oauth2.Tokens, w http.ResponseWriter, r *http.Request, c martini.Context) {
		if token == nil || token.Expired() {
			next := url.QueryEscape(r.URL.RequestURI())
			http.Redirect(w, r, oauth2.PathLogin+"?next="+next, 302)
			return
		}
		id, err := GetId(token.Access())
		if err != nil {
			log.Printf("Error getting player token id:", err.Error())
			http.Redirect(w, r, "/error", 302)
			return
		}
		user := ols.GetUserDAO().GetUserFB(id)
		if user.LeagueId == 0 {
			next := url.QueryEscape(r.URL.RequestURI())
			http.Redirect(w, r, "/register?next="+next, 302)
		}

		// TODO - fix this
		if !true {
			http.Redirect(w, r, "/error", 302)
		}
		c.Map(user)
		c.Next()

	}
}
func (slvgs *softLayer_Virtual_Guest_Service) CreateArchiveTransaction(instanceId int, groupName string, blockDevices []datatypes.SoftLayer_Virtual_Guest_Block_Device, note string) (datatypes.SoftLayer_Provisioning_Version1_Transaction, error) {
	groupName = url.QueryEscape(groupName)
	note = url.QueryEscape(note)

	parameters := datatypes.SoftLayer_Virtual_GuestInitParameters{
		Parameters: []interface{}{groupName, blockDevices, note},
	}

	requestBody, err := json.Marshal(parameters)
	if err != nil {
		return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
	}

	response, errorCode, err := slvgs.client.GetHttpClient().DoRawHttpRequest(fmt.Sprintf("%s/%d/createArchiveTransaction.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
	if err != nil {
		return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
	}

	if common.IsHttpErrorCode(errorCode) {
		errorMessage := fmt.Sprintf("softlayer-go: could not SoftLayer_Virtual_Guest#createArchiveTransaction, HTTP error code: '%d'", errorCode)
		return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, errors.New(errorMessage)
	}

	transaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
	err = json.Unmarshal(response, &transaction)
	if err != nil {
		return datatypes.SoftLayer_Provisioning_Version1_Transaction{}, err
	}

	return transaction, nil
}
// Generates our signature - based on: https://web-payments.org/specs/ED/http-signatures/2014-02-01/#page-3 HMAC signing
func (hm HMACMiddleware) generateSignatureFromRequest(r *http.Request, secret string) string {
	//method := strings.ToUpper(r.Method)
	//base_url := url.QueryEscape(r.URL.RequestURI())

	date_header := url.QueryEscape(r.Header.Get(DateHeaderSpec))

	// Not using form params for now, just date string
	//params := url.QueryEscape(hm.parseFormParams(r.Form))

	// Prep the signature string
	signatureString := strings.ToLower(DateHeaderSpec) + ":" + date_header

	log.Debug("Signature string before encoding: ", signatureString)

	// Encode it
	key := []byte(secret)
	h := hmac.New(sha1.New, key)
	h.Write([]byte(signatureString))

	encodedString := base64.StdEncoding.EncodeToString(h.Sum(nil))
	log.Debug("Encoded signature string: ", encodedString)
	log.Debug("URL Encoded: ", url.QueryEscape(encodedString))

	// Return as base64
	return encodedString
}
Example #17
0
func (h *httpGetter) Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error {
	u := fmt.Sprintf(
		"%v%v/%v",
		h.baseURL,
		url.QueryEscape(in.GetGroup()),
		url.QueryEscape(in.GetKey()),
	)
	req, err := http.NewRequest("GET", u, nil)
	if err != nil {
		return err
	}
	tr := http.DefaultTransport
	if h.transport != nil {
		tr = h.transport(context)
	}
	res, err := tr.RoundTrip(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("server returned: %v", res.Status)
	}
	// TODO: avoid this garbage.
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return fmt.Errorf("reading response body: %v", err)
	}
	err = proto.Unmarshal(b, out)
	if err != nil {
		return fmt.Errorf("decoding response body: %v", err)
	}
	return nil
}
Example #18
0
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) {
	sid := manager.sessionId(r)
	cookie, err := r.Cookie(manager.cookieName)
	if err != nil && cookie.Value == "" {
		//delete old cookie
		session, _ = manager.provider.SessionRead(sid)
		cookie = &http.Cookie{Name: manager.cookieName,
			Value:    url.QueryEscape(sid),
			Path:     "/",
			HttpOnly: true,
			Secure:   manager.secure,
		}
	} else {
		oldsid, _ := url.QueryUnescape(cookie.Value)
		session, _ = manager.provider.SessionRegenerate(oldsid, sid)
		cookie.Value = url.QueryEscape(sid)
		cookie.HttpOnly = true
		cookie.Path = "/"
	}
	if manager.maxage >= 0 {
		cookie.MaxAge = manager.maxage
	}
	http.SetCookie(w, cookie)
	r.AddCookie(cookie)
	return
}
Example #19
0
func (s *httpServer) emptyTopicHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		s.ctx.nsqadmin.logf("ERROR: invalid %s to POST only method", req.Method)
		http.Error(w, "INVALID_REQUEST", 500)
		return
	}
	reqParams := &http_api.PostParams{req}

	topicName, err := reqParams.Get("topic")
	if err != nil {
		http.Error(w, "MISSING_ARG_TOPIC", 500)
		return
	}

	producerAddrs := s.getProducers(topicName)
	s.performVersionNegotiatedRequestsToNSQD(
		s.ctx.nsqadmin.opts.NSQLookupdHTTPAddresses,
		producerAddrs,
		"empty_topic",
		"topic/empty",
		fmt.Sprintf("topic=%s",
			url.QueryEscape(topicName)))

	s.notifyAdminAction("empty_topic", topicName, "", "", req)

	http.Redirect(w, req, fmt.Sprintf("/topic/%s", url.QueryEscape(topicName)), 302)
}
func (c *Client) IndexTypeBulk(index string, docType string, items []*BulkRequest) (*BulkResponse, error) {
	reqUrl := fmt.Sprintf("http://%s/%s/%s/_bulk", c.Addr,
		url.QueryEscape(index),
		url.QueryEscape(docType))

	return c.DoBulk(reqUrl, items)
}
func main() {
	flag.Parse()
	checkArguments()

	check := nagiosplugin.NewCheck()
	defer check.Finish()

	var data map[string]interface{}
	queryApi(parseUrl(*api_url)+"/streams/"+url.QueryEscape(*stream)+"/alerts/check", url.QueryEscape(*user), url.QueryEscape(*pass), &data)

	total := data["total_triggered"].(float64)
	results := data["results"].([]interface{})

	var stream_title string

	queryApi(parseUrl(*api_url)+"/streams/"+url.QueryEscape(*stream), url.QueryEscape(*user), url.QueryEscape(*pass), &data)
	stream_title = data["title"].(string)

	for i, result := range results {
		i = i
		mappedResult := result.(map[string]interface{})
		mappedCondition := mappedResult["condition"].(map[string]interface{})
		if *condition != "<ID>" && *condition == mappedCondition["id"] && mappedResult["triggered"] == true {
			nagiosplugin.Exit(nagiosplugin.CRITICAL, "Alert triggered for stream '"+stream_title+"' condition: "+*condition)
		}
	}

	if total > 0 && *condition == "<ID>" {
		nagiosplugin.Exit(nagiosplugin.CRITICAL, fmt.Sprintf("%g", total)+" alert/s triggered for stream "+stream_title)
	}

	check.AddResult(nagiosplugin.OK, "No stream alerts triggered for stream: "+stream_title)
}
Example #22
0
func runChild(distChan chan string, wg *sync.WaitGroup, node string) {
	defer wg.Done()
	toCall := fmt.Sprintf(
		"http://%s/t=%d&m=%s&c=%d&n=%d&k=%t&url=%s",
		node,
		*numThreads,
		*method,
		*numConnections,
		*totalCalls,
		*disableKeepAlives,
		url.QueryEscape(url.QueryEscape(target)),
	)
	fmt.Println(toCall)
	resp, err := http.Get(toCall)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	distChan <- string(body)
}
Example #23
0
func buildUrl(command string, params map[string]string) (string, error) {
	apiKey, err := config.GetString("iaas:cloudstack:api-key")
	if err != nil {
		return "", err
	}
	secretKey, err := config.GetString("iaas:cloudstack:secret-key")
	if err != nil {
		return "", err
	}
	params["command"] = command
	params["response"] = "json"
	params["apiKey"] = apiKey
	var sorted_keys []string
	for k := range params {
		sorted_keys = append(sorted_keys, k)
	}
	sort.Strings(sorted_keys)
	var string_params []string
	for _, key := range sorted_keys {
		queryStringParam := fmt.Sprintf("%s=%s", key, url.QueryEscape(params[key]))
		string_params = append(string_params, queryStringParam)
	}
	queryString := strings.Join(string_params, "&")
	digest := hmac.New(sha1.New, []byte(secretKey))
	digest.Write([]byte(strings.ToLower(queryString)))
	signature := base64.StdEncoding.EncodeToString(digest.Sum(nil))
	cloudstackUrl, err := config.GetString("iaas:cloudstack:url")
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s?%s&signature=%s", cloudstackUrl, queryString, url.QueryEscape(signature)), nil
}
Example #24
0
// Write logs to server
func (c *Cmd) _flushLogs() {
	// Only if this has a signature, else it is local
	if len(c.Signature) < 1 {
		return
	}

	// To JSON
	m := make(map[string][]string)
	m["output"] = c.BufOutput
	m["error"] = c.BufOutputErr
	bytes, je := json.Marshal(m)
	if je != nil {
		log.Printf("Failed to convert logs to JSON: %s", je)
		return
	}

	// Post to server
	uri := fmt.Sprintf("client/%s/cmd/%s/logs", url.QueryEscape(client.Id), url.QueryEscape(c.Id))
	b, e := client._req("PUT", uri, bytes)
	if e != nil || len(b) < 1 {
		log.Printf("Failed log write: %s", e)
	}

	// Clear buffers
	c.BufOutput = make([]string, 0)
	c.BufOutputErr = make([]string, 0)
}
func (p *AccessTokenServer) getToken() (*accessToken, error) {
	url := fmt.Sprintf(accessTokenApi, url.QueryEscape(p.appId), url.QueryEscape(p.appSecret))
	httpResp, err := http.DefaultClient.Get(url)
	if err != nil {
		return nil, err
	}
	defer httpResp.Body.Close()

	if httpResp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http.Status: %s", httpResp.Status)
	}

	var result struct {
		accessToken
		Error
	}

	if err = json.NewDecoder(httpResp.Body).Decode(&result); err != nil {
		return nil, err
	}

	if result.ErrCode != 0 {
		return nil, result.Error
	}

	return &result.accessToken, nil

}
Example #26
0
File: fop.go Project: mtinf/qshell
func Pfop(cmd string, params ...string) {
	if len(params) == 3 || len(params) == 4 || len(params) == 5 {
		bucket := params[0]
		key := params[1]
		fops := params[2]
		host := params[3]
		gErr := accountS.Get()
		if gErr != nil {
			fmt.Println(gErr)
			return
		}

		mac := digest.Mac{accountS.AccessKey, []byte(accountS.SecretKey)}
		bodyStr := fmt.Sprintf("bucket=%s&key=%s&fops=%s", url.QueryEscape(bucket), url.QueryEscape(key), url.QueryEscape(fops))
		h := hmac.New(sha1.New, []byte(mac.SecretKey))
		signingStr := "/pfop\n" + bodyStr
		h.Write([]byte(signingStr))
		sign := h.Sum(nil)
		encodedSign := base64.URLEncoding.EncodeToString(sign)
		authorization := "QBox " + mac.AccessKey + ":" + string(encodedSign)
		client := &http.Client{}
		r, err := http.NewRequest("POST", fmt.Sprintf("%s/pfop", host), bytes.NewBufferString(bodyStr))
		if err != nil {
			fmt.Println(err)
			return
		}
		r.Header.Add("Authorization", authorization)
		resp, _ := client.Do(r)
		result, _ := ioutil.ReadAll(resp.Body)
		fmt.Println(string(result))
	} else {
		CmdHelp(cmd)
	}
}
// ListPreparer prepares the List request.
func (client WorkflowTriggersClient) ListPreparer(resourceGroupName string, workflowName string, top *int, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": url.QueryEscape(resourceGroupName),
		"subscriptionId":    url.QueryEscape(client.SubscriptionID),
		"workflowName":      url.QueryEscape(workflowName),
	}

	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if top != nil {
		queryParameters["$top"] = top
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	return autorest.Prepare(&http.Request{},
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/triggers/"),
		autorest.WithPathParameters(pathParameters),
		autorest.WithQueryParameters(queryParameters))
}
Example #28
0
func (params Params) encodeFormUrlEncoded(writer io.Writer) (mime string, err error) {
	var jsonStr []byte
	written := false

	for k, v := range params {
		if written {
			io.WriteString(writer, "&")
		}

		io.WriteString(writer, url.QueryEscape(k))
		io.WriteString(writer, "=")

		if reflect.TypeOf(v).Kind() == reflect.String {
			io.WriteString(writer, url.QueryEscape(reflect.ValueOf(v).String()))
		} else {
			jsonStr, err = json.Marshal(v)

			if err != nil {
				return
			}

			io.WriteString(writer, url.QueryEscape(string(jsonStr)))
		}

		written = true
	}

	mime = _MIME_FORM_URLENCODED
	return
}
// GetConfiguration reads and returns the actual configuration
// of the resources described by a cached configuration.
func (d *deployer) GetConfiguration(cached *Configuration) (*Configuration, error) {
	errors := &Error{}
	actual := &Configuration{}
	for _, resource := range cached.Resources {
		rtype := url.QueryEscape(resource.Type)
		rname := url.QueryEscape(resource.Name)
		url := fmt.Sprintf("%s/%s/%s", d.getBaseURL(), rtype, rname)
		body, err := d.callService("GET", url, nil, func(e error) error {
			return fmt.Errorf("cannot get configuration for resource (%s)", e)
		})
		if err != nil {
			log.Println(errors.appendError(err))
			continue
		}

		if len(body) != 0 {
			result := &Resource{Name: resource.Name, Type: resource.Type}
			if err := yaml.Unmarshal(body, &result.Properties); err != nil {
				return nil, fmt.Errorf("cannot get configuration for resource (%v)", err)
			}

			actual.Resources = append(actual.Resources, result)
		}
	}

	if len(errors.errors) > 0 {
		return nil, errors
	}

	return actual, nil
}
Example #30
0
File: http.go Project: jsocol/nsq
func (s *httpServer) emptyTopicHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		log.Printf("ERROR: invalid %s to POST only method", req.Method)
		http.Error(w, "INVALID_REQUEST", 500)
		return
	}
	reqParams := &util.PostParams{req}

	topicName, err := reqParams.Get("topic")
	if err != nil {
		http.Error(w, "MISSING_ARG_TOPIC", 500)
		return
	}

	producers := s.getProducers(topicName)
	for _, addr := range producers {
		endpoint := fmt.Sprintf("http://%s/empty_topic?topic=%s", addr, url.QueryEscape(topicName))
		log.Printf("NSQD: calling %s", endpoint)

		_, err := util.ApiRequest(endpoint)
		if err != nil {
			log.Printf("ERROR: nsqd %s - %s", endpoint, err.Error())
			continue
		}
	}

	s.notifyAdminAction("empty_topic", topicName, "", "", req)

	http.Redirect(w, req, fmt.Sprintf("/topic/%s", url.QueryEscape(topicName)), 302)
}