本文整理汇总了Golang中net/url.QueryEscape函数的典型用法代码示例。如果您正苦于以下问题:Golang QueryEscape函数的具体用法?Golang QueryEscape怎么用?Golang QueryEscape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了QueryEscape函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: pauseChannelHandler
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)
}
示例2: Encode
// 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()
}
示例3: newAuthenticatedRequest
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
}
示例4: ServeHTTP
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)
}
示例5: Push
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
}
示例6: ListAllPreparer
// 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))
}
示例7: pauseChannelHandler
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)
}
示例8: emptyChannelHandler
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)
}
示例9: parseFormParams
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
}
示例10: SearchAvailableWithOptions
// 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
}
示例11: ListJobHistoryPreparer
// 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))
}
示例12: configure
// 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
}
示例13: Permissions
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()
}
}
示例14: CreateArchiveTransaction
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
}
示例15: generateSignatureFromRequest
// 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
}