本文整理汇总了Golang中net/url.Query函数的典型用法代码示例。如果您正苦于以下问题:Golang Query函数的具体用法?Golang Query怎么用?Golang Query使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Query函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: GenReqUrl
//生成短信请求url
func (p *phoneSms_t) GenReqUrl(recNum string, smsParam string, SmsFreeSignName string, SmsTemplateCode string) (value string, err error) {
//时间戳格式"2015-11-26 20:32:42"
var timeStamp = zzcommon.StringSubstr(time.Now().String(), 19)
var strMd5 string = p.genSign(recNum, smsParam, timeStamp, SmsFreeSignName, SmsTemplateCode)
var reqUrl = p.UrlPattern +
"?sign=" + strMd5 +
"&app_key=" + p.AppKey +
"&method=" + p.Method +
"&rec_num=" + recNum +
"&sign_method=" + p.SignMethod +
"&sms_free_sign_name=" + SmsFreeSignName +
"&sms_param=" + smsParam +
"&sms_template_code=" + SmsTemplateCode +
"&sms_type=" + p.SmsType +
"×tamp=" + timeStamp +
"&v=" + p.Versions
url, err := url.Parse(reqUrl)
if nil != err {
fmt.Println("######PhoneRegister.genReqUrl err:", reqUrl, err)
return reqUrl, err
}
reqUrl = p.UrlPattern + "?" + url.Query().Encode()
return reqUrl, err
}
示例2: createYoutubeLink
func createYoutubeLink(src io.Reader) {
var ids []string
scanner := bufio.NewScanner(src)
for scanner.Scan() {
line := scanner.Text()
url, err := url.Parse(line)
if err != nil {
logrus.WithFields(logrus.Fields{"err": err, "line": line}).Error("This line is not a proper url")
continue
}
values := url.Query()
if id, ok := values["v"]; !ok {
logrus.WithField("line", line).Error("This line is not properly formed. Could not find id of video")
} else {
ids = append(ids, id[0])
}
}
if len(ids) <= 0 {
logrus.Error("Could not parse a single line to produce a youtube playlist")
os.Exit(-1)
} else {
var playListUrl = "https://www.youtube.com/watch_videos?video_ids=" + strings.Join(ids, ",")
fmt.Println("URL of the playlist: ", playListUrl)
}
}
示例3: GetHistory
func (ch Channel) GetHistory(oldest int64) ([]Message, error) {
token := os.Getenv("SLACK_API_TOKEN")
var chan_res ChannelHistoryReponse
url, _ := url.Parse("https://slack.com/api/channels.history")
q := url.Query()
q.Set("token", token)
q.Set("channel", ch.ID)
q.Set("oldest", strconv.FormatInt(oldest, 10))
url.RawQuery = q.Encode()
res, err := http.Get(url.String())
defer res.Body.Close()
if err != nil {
fmt.Println(err)
return nil, err
}
decoder := json.NewDecoder(res.Body)
err2 := decoder.Decode(&chan_res)
if err2 != nil {
return nil, err
}
if !chan_res.OK {
return nil, fmt.Errorf("API eturns not OK")
}
return chan_res.Messages, nil
}
示例4: ParseURI
// ParseURI parses a database URI into ConnConfig
func ParseURI(uri string) (ConnConfig, error) {
var cp ConnConfig
url, err := url.Parse(uri)
if err != nil {
return cp, err
}
if url.User != nil {
cp.User = url.User.Username()
cp.Password, _ = url.User.Password()
}
parts := strings.SplitN(url.Host, ":", 2)
cp.Host = parts[0]
if len(parts) == 2 {
p, err := strconv.ParseUint(parts[1], 10, 16)
if err != nil {
return cp, err
}
cp.Port = uint16(p)
}
cp.Database = strings.TrimLeft(url.Path, "/")
err = configSSL(url.Query().Get("sslmode"), &cp)
if err != nil {
return cp, err
}
return cp, nil
}
示例5: putCAS
// putCAS is used to do a PUT with optional CAS
func (c *Client) putCAS(key string, value []byte, flags, index uint64, cas bool) (bool, error) {
url := c.pathURL(key)
query := url.Query()
if cas {
query.Set("cas", strconv.FormatUint(index, 10))
}
query.Set("flags", strconv.FormatUint(flags, 10))
url.RawQuery = query.Encode()
req := http.Request{
Method: "PUT",
URL: url,
Body: ioutil.NopCloser(bytes.NewReader(value)),
}
req.ContentLength = int64(len(value))
resp, err := c.config.HTTPClient.Do(&req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false, fmt.Errorf("unexpected response code: %d", resp.StatusCode)
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, resp.Body); err != nil {
return false, fmt.Errorf("failed to read response: %v", err)
}
res := strings.Contains(string(buf.Bytes()), "true")
return res, nil
}
示例6: GetMatch
// GetMatch returns a *dota.Match parsed out of the Dota2 WebAPI.
func (wa *WebAPI) GetMatch(id int) (*dota.Match, error) {
url := &url.URL{
Scheme: "https",
Path: "api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/",
}
query := url.Query()
query.Set("key", wa.key)
query.Set("match_id", strconv.Itoa(id))
url.RawQuery = query.Encode()
resp, err := http.Get(url.String())
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var md request.GetMatchDetails
err = json.Unmarshal(data, &md)
if err != nil {
return nil, err
}
return md.ParseMatch()
}
示例7: GetCampaignPage
// GetCampaignPage returns all the campaigns from the supplied page
func (ps *ProfitShare) GetCampaignPage(page int) ([]Campaign, Paginator, error) {
url, err := url.Parse("affiliate-campaigns")
if err != nil {
return []Campaign{}, Paginator{}, err
}
q := url.Query()
q.Add("page", fmt.Sprintf("%d", page))
url.RawQuery = q.Encode()
body, err := ps.Get(url.String())
if err != nil {
return []Campaign{}, Paginator{}, err
}
rez := map[string]CampaignsResult{}
err = json.Unmarshal(body, &rez)
if err != nil {
return []Campaign{}, Paginator{}, err
}
return rez["result"].Campaigns, rez["result"].Paginator, nil
}
示例8: PrepGetObjects
// PrepGetObjects creates an http.Request from a GetObjectRequest
func PrepGetObjects(r GetObjectRequest) (*http.Request, error) {
url, err := url.Parse(r.URL)
if err != nil {
return nil, err
}
values := url.Query()
// required
values.Add("Resource", r.Resource)
values.Add("Type", r.Type)
// optional
optionalString := OptionalStringValue(values)
// one or the other _MUST_ be present
optionalString("ID", r.ID)
optionalString("UID", r.UID)
// truly optional
optionalString("ObjectData", strings.Join(r.ObjectData, ","))
optionalInt := OptionalIntValue(values)
optionalInt("Location", r.Location)
method := DefaultHTTPMethod
if r.HTTPMethod != "" {
method = r.HTTPMethod
}
url.RawQuery = values.Encode()
return http.NewRequest(method, url.String(), nil)
}
示例9: do
func (remote *Remote) do(command Command, parameters map[string]string) (string, error) {
urlString := fmt.Sprintf(requestString, remote.Host, remote.Port, resources[command])
url, err := url.Parse(urlString)
if err != nil {
fmt.Println(err)
return "", err
}
if parameters != nil {
urlQuery := url.Query()
for key, value := range parameters {
urlQuery.Set(key, value)
}
url.RawQuery = urlQuery.Encode()
}
client := new(http.Client)
req, err := http.NewRequest("GET", url.String(), nil)
req.SetBasicAuth(remote.Username, remote.Password)
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return "", err
}
return string(body), nil
}
示例10: GetAdvertisers
// GetAdvertisers returns a list of advertise from a period of time to another
func (ps *ProfitShare) GetAdvertisers(from time.Time, to time.Time) ([]Advertiser, error) {
dateFormat := "2006-01-02"
url, err := url.Parse("affiliate-advertisers")
if err != nil {
return []Advertiser{}, err
}
q := url.Query()
q.Add("date_from", from.Format(dateFormat))
q.Add("date_to", to.Format(dateFormat))
url.RawQuery = q.Encode()
body, err := ps.Get(url.String())
if err != nil {
return []Advertiser{}, err
}
var rez map[string]map[string]Advertiser
_ = json.Unmarshal(body, &rez)
var ret []Advertiser
for _, item := range rez["result"] {
ret = append(ret, item)
}
return ret, nil
}
示例11: NewClient
func NewClient(uri string, opts *Options) (client *Client, err error) {
url, err := url.Parse(uri)
if err != nil {
return
}
url.Path = path.Join("/socket.io", url.Path)
url.Path = url.EscapedPath()
if strings.HasSuffix(url.Path, "socket.io") {
url.Path += "/"
}
q := url.Query()
for k, v := range opts.Query {
q.Set(k, v)
}
url.RawQuery = q.Encode()
socket, err := engineio.NewClientConn(opts.Transport, url)
if err != nil {
return
}
client = &Client{
opts: opts,
conn: socket,
events: make(map[string]*caller),
acks: make(map[int]*caller),
}
go client.readLoop()
return
}
示例12: ListByService
func (r *EnvironmentVariableResource) ListByService(serviceURL string) ([]*EnvironmentVariable, error) {
url := r.client.buildBaseURL("envvars/")
q := url.Query()
q.Set("service", serviceURL)
url.RawQuery = q.Encode()
return r.findMany(url)
}
示例13: Gzip
func Gzip(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// @TODO(mark): Swap this for some handler flags
url, err := url.Parse(r.URL.String())
queryParams := url.Query()
_, found := queryParams[queryStringKey]
if found {
handler.ServeHTTP(w, r)
return
}
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
handler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz, err := gzip.NewWriterLevel(w, gzip.BestCompression)
if err != nil {
http.Error(w, "Error with gzip compression", http.StatusInternalServerError)
return
}
defer gz.Close()
gzw := gzipResponseWriter{
Writer: gz,
ResponseWriter: w,
}
handler.ServeHTTP(gzw, r)
})
}
示例14: PrepUrl
// PrepUrl handles the parsing and setup for all api calls. The encoded url string is passed
// along with a set of param. Params are looped and injected into the master url
func (l *Client) PrepUrl(endpoint string, params url.Values, dataKey bool) (string, error) {
// parse the url into native http.URL
url, err := url.Parse(fmt.Sprintf("%s/%s", l.BaseUrl(), endpoint))
if err != nil {
return "", err
}
values := url.Query()
// add the api key
if params != nil {
for key, val := range params {
for _, v := range val {
values.Add(key, v)
}
}
}
// if there is a data key use that by default, if not use the main api key
// assumption here is that if its a data key there are specific reasons
if dataKey {
values.Add("key", l.dataApiKey)
} else {
values.Add("key", l.apiKey)
}
// encode the final url so we can return string and make call
url.RawQuery = values.Encode()
return url.String(), nil
}
示例15: TestReduceError
func (mrt *MapreduceTests) TestReduceError(c *ck.C) {
return
u := testReduceError{}
job := mrt.setup(&u, &u.SimpleTasks)
defer u.SimpleTasks.gather()
ds := appwrap.NewLocalDatastore()
_, err := Run(appwrap.StubContext(), ds, job)
c.Check(err, ck.Equals, nil)
resultUrl := <-u.SimpleTasks.done
url, err := url.Parse(resultUrl)
c.Check(err, ck.IsNil)
fields := url.Query()
c.Check(err, ck.IsNil)
c.Check(fields["status"][0], ck.Equals, "error")
c.Check(fields["error"][0], ck.Equals, "error retrying: maxium retries exceeded (task failed due to: reduce had an error)")
// see if we handle retries properly
v := testReduceError{succeedThreshold: u.count / 2}
job = mrt.setup(&v, &v.SimpleTasks)
defer v.SimpleTasks.gather()
_, err = Run(appwrap.StubContext(), ds, job)
c.Check(err, ck.Equals, nil)
resultUrl = <-v.SimpleTasks.done
c.Check(strings.Index(resultUrl, "status=done"), ck.Equals, 6)
}