本文整理匯總了Golang中net/url.Values函數的典型用法代碼示例。如果您正苦於以下問題:Golang Values函數的具體用法?Golang Values怎麽用?Golang Values使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Values函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: BuildImage
// BuildImage builds an image from a tarball's url or a Dockerfile in the input
// stream.
//
// See https://goo.gl/xySxCe for more details.
func (c *Client) BuildImage(opts BuildImageOptions) error {
if opts.OutputStream == nil {
return ErrMissingOutputStream
}
headers, err := headersWithAuth(opts.Auth, c.versionedAuthConfigs(opts.AuthConfigs))
if err != nil {
return err
}
if opts.Remote != "" && opts.Name == "" {
opts.Name = opts.Remote
}
if opts.InputStream != nil || opts.ContextDir != "" {
headers["Content-Type"] = "application/tar"
} else if opts.Remote == "" {
return ErrMissingRepo
}
if opts.ContextDir != "" {
if opts.InputStream != nil {
return ErrMultipleContexts
}
var err error
if opts.InputStream, err = createTarStream(opts.ContextDir, opts.Dockerfile); err != nil {
return err
}
}
qs := queryString(&opts)
if len(opts.Ulimits) > 0 {
if b, err := json.Marshal(opts.Ulimits); err == nil {
item := url.Values(map[string][]string{})
item.Add("ulimits", string(b))
qs = fmt.Sprintf("%s&%s", qs, item.Encode())
}
}
if len(opts.BuildArgs) > 0 {
v := make(map[string]string)
for _, arg := range opts.BuildArgs {
v[arg.Name] = arg.Value
}
if b, err := json.Marshal(v); err == nil {
item := url.Values(map[string][]string{})
item.Add("buildargs", string(b))
qs = fmt.Sprintf("%s&%s", qs, item.Encode())
}
}
return c.stream("POST", fmt.Sprintf("/build?%s", qs), streamOptions{
setRawTerminal: true,
rawJSONStream: opts.RawJSONStream,
headers: headers,
in: opts.InputStream,
stdout: opts.OutputStream,
inactivityTimeout: opts.InactivityTimeout,
context: opts.Context,
})
}
示例2: auth
func auth(w http.ResponseWriter, r *http.Request) {
//form the query with the oauth paramters of our client application
query := url.Values(map[string][]string{
"response_type": []string{"code"},
"client_id": []string{clientId},
"redirect_uri": []string{redirect},
})
target, _ := authUrl.Parse(authPath)
target.RawQuery = url.Values(query).Encode()
//redirect the user to the auth server
log.Printf("redirecting user agent to %v", target)
http.Redirect(w, r, target.String(), http.StatusFound)
}
示例3: SetIntArray
func (oa optionalArgs) SetIntArray(k string, ia []int) {
switch n := len(ia); {
case n == 0:
return
case n == 1:
url.Values(oa).Set(k, strconv.Itoa(ia[0]))
default:
strIds := make([]string, n)
for i, v := range ia {
strIds[i] = strconv.Itoa(v)
}
url.Values(oa).Set("ids", strings.Join(strIds, ","))
}
}
示例4: SetIdArray
func (oa optionalArgs) SetIdArray(k string, ia []Id) {
switch n := len(ia); {
case n == 0:
return
case n == 1:
url.Values(oa).Set(k, strconv.FormatUint(uint64(ia[0]), 10))
default:
strIds := make([]string, n)
for i, v := range ia {
strIds[i] = strconv.FormatUint(uint64(v), 10)
}
url.Values(oa).Set("ids", strings.Join(strIds, ","))
}
}
示例5: getToken
/* getToken gets the authentication token for the given username and
password */
func getToken(u, p string) (string, error) {
/* Send the request */
res, err := http.PostForm(authURL, url.Values(map[string][]string{
"email": {u},
"password": {p},
}))
if nil != err {
return "", err
}
defer res.Body.Close()
/* Read body into buffer */
buf := &bytes.Buffer{}
_, err = io.Copy(buf, res.Body)
if nil != err {
return "", err
}
/* If we're not authorized, :( */
if "Unauthorized" == buf.String() {
return "", fmt.Errorf("unauthorized")
}
/* Struct into which to decode token */
rs := struct {
Ok int
Token string
}{}
/* Unmarshal the JSON */
if err := json.Unmarshal(buf.Bytes(), &rs); nil != err {
return "", err
}
return rs.Token, nil
}
示例6: CreateAuthenticationRequest
func (q Query) CreateAuthenticationRequest(Realm, ReturnTo string) string {
claimedID := q.ClaimedID
if claimedID == "" {
claimedID = "http://specs.openid.net/auth/2.0/identifier_select"
}
p := map[string][]string{
"openid.ns": []string{"http://specs.openid.net/auth/2.0"},
"openid.mode": []string{"checkid_setup"},
"openid.return_to": []string{Realm + ReturnTo},
"openid.realm": []string{Realm},
"openid.claimed_id": []string{claimedID},
"openid.identity": []string{claimedID},
"openid.ns.ax": []string{"http://openid.net/srv/ax/1.0"},
"openid.ax.mode": []string{"fetch_request"},
"openid.ax.required": []string{"email"},
"openid.ax.type.email": []string{"http://axschema.org/contact/email"},
}
url_ := q.OPEndpointURL
if strings.Index(url_, "?") == -1 {
url_ = url_ + "?"
} else {
url_ = url_ + "&"
}
return url_ + url.Values(p).Encode()
}
示例7: Async
// 同步
func (this *MemberC) Async(ctx *echo.Context) error {
var rlt AsyncResult
var form = url.Values(ctx.Request().Form)
var mut, aut, kvMut, kvAut int
memberId := GetMemberId(ctx)
mut, _ = strconv.Atoi(form.Get("member_update_time"))
aut, _ = strconv.Atoi(form.Get("account_update_time"))
mutKey := fmt.Sprintf("%s%d", variable.KvMemberUpdateTime, memberId)
sto.Get(mutKey, &kvMut)
autKey := fmt.Sprintf("%s%d", variable.KvAccountUpdateTime, memberId)
sto.Get(autKey, &kvAut)
if kvMut == 0 {
m := dps.MemberService.GetMember(memberId)
kvMut = int(m.UpdateTime)
sto.Set(mutKey, kvMut)
}
//kvAut = 0
if kvAut == 0 {
acc := dps.MemberService.GetAccount(memberId)
kvAut = int(acc.UpdateTime)
sto.Set(autKey, kvAut)
}
rlt.MemberId = memberId
rlt.MemberUpdated = kvMut != mut
rlt.AccountUpdated = kvAut != aut
return ctx.JSON(http.StatusOK, rlt)
}
示例8: queryString
func queryString(opts interface{}) string {
if opts == nil {
return ""
}
value := reflect.ValueOf(opts)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
if value.Kind() != reflect.Struct {
return ""
}
items := url.Values(map[string][]string{})
for i := 0; i < value.NumField(); i++ {
field := value.Type().Field(i)
if field.PkgPath != "" {
continue
}
key := field.Tag.Get("qs")
if key == "" {
key = strings.ToLower(field.Name)
} else if key == "-" {
continue
}
addQueryStringValue(items, key, value.Field(i))
}
return items.Encode()
}
示例9: ParseControlFile
// ParseControlFile reads debian control file format into map[string][]string
func ParseControlFile(data string) url.Values {
ret := url.Values(make(map[string][]string))
arr := strings.Split(data, "\n")
cur := ""
for lineno, line := range arr {
if line == "" {
// skip empty line
continue
}
lineno++
tag := ctrlRegexp.Find([]byte(line))
if tag == nil {
if _, ok := ret[cur]; !ok {
log.Printf("Ignoring format error at line#%d: %#v", lineno, line)
continue
}
ret[cur] = append(ret[cur], line)
continue
}
cur = string(tag[0 : len(tag)-1])
ret[cur] = make([]string, 0)
if len(line) > len(tag)+1 {
ret.Add(cur, line[len(tag)+1:])
}
}
return ret
}
示例10: proxyRequest
// Round trips the request to the selected proxy and writes back the response
func (p *Handler) proxyRequest(w http.ResponseWriter, r *http.Request) error {
// Lookup the Proxy registered for the given pair: method, path.
proxy, params, _ := p.GetRouter().Lookup(r.Method, r.URL.Path)
if len(params) > 0 {
// fmt.Printf("params: %+v \n", params)
r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
}
if proxy == nil {
p.logger.Warn("Handler failed to route: %s ", r.URL.Path)
return errors.FromStatus(http.StatusBadGateway)
}
// Create a unique request with sequential ids that will be passed to all interfaces.
fctx := context.NewFlowContext(r, w, atomic.AddInt64(&p.lastRequestId, 1), nil)
// The roundtrip thru the whole pipeline of modules
response, err := proxy.ProcessChain(fctx)
// Preparing the response back to the client if applicable
if response != nil {
httputils.CopyHeaders(w.Header(), response.Header)
w.WriteHeader(response.StatusCode)
if response.Body == nil {
logutils.FileLogger.Warn("Empty body contained on the response")
} else {
io.Copy(w, response.Body)
defer response.Body.Close()
}
return nil
} else {
return err
}
}
示例11: TestResourceNotImplementedMethods
func TestResourceNotImplementedMethods(t *testing.T) {
mux := setupMux(nil, nil)
go func() {
http.ListenAndServe(":8188", mux)
}()
resp, err := http.Get("http://localhost:8188/rest/somewire")
checkHttpStatus(t, resp, err, http.StatusNotImplemented)
body := "{}"
resp, err = http.Post("http://localhost:8188/rest/somewire", "text/json", strings.NewReader(body))
checkHttpStatus(t, resp, err, http.StatusNotImplemented)
data := url.Values(map[string][]string{"nothing": []string{"bogus"}})
resp, err = http.PostForm("http://localhost:8188/rest/somewire", data)
checkHttpStatus(t, resp, err, http.StatusNotImplemented)
resp, err = http.Post("http://localhost:8188/rest/somewire/2", "text/json", strings.NewReader(body))
checkHttpStatus(t, resp, err, http.StatusBadRequest)
resp, err = http.Get("http://localhost:8188/rest/somewire/3")
checkHttpStatus(t, resp, err, http.StatusNotImplemented)
client := new(http.Client)
req := makeReq(t, "PUT", "http://localhost:8188/rest/somewire/4", "{}")
resp, err = client.Do(req)
checkHttpStatus(t, resp, err, http.StatusNotImplemented)
req = makeReq(t, "DELETE", "http://localhost:8188/rest/somewire/5", "")
resp, err = client.Do(req)
checkHttpStatus(t, resp, err, http.StatusNotImplemented)
}
示例12: resource
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
}
示例13: ServeHTTP
// Required by http.Handler interface. This method is invoked by the
// http server and will handle all page routing
func (mux *RERouteMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestPath := r.URL.Path
for _, router := range mux.routers {
// if this router does not match the url, then continue
if !router.regex.MatchString(requestPath) {
continue
}
// get submatches: the 1st is the entire url, others are
// parameters
submatches := router.regex.FindStringSubmatch(requestPath)
// just check the length to get better efficiency
if len(submatches[0]) != len(requestPath) {
continue
}
// encode the parameters into r.URL.RawQuery
if len(router.params) > 0 {
values := r.URL.Query()
for i, match := range submatches[1:] {
values.Add(router.params[i], match)
}
r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
}
router.handler(w, r)
return
}
http.NotFound(w, r)
}
示例14: ServeHTTP
// match requests against registered handlers, serve http
func (self *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, h := range self.routes[r.Method] {
if params, ok := h.parse(r.URL.Path); ok {
if len(params) > 0 {
r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
}
h.ServeHTTP(w, r)
return
}
}
allowed := make([]string, 0, len(self.routes))
for method, routes := range self.routes {
if method == r.Method {
continue
}
for _, h := range routes {
if _, ok := h.parse(r.URL.Path); ok {
allowed = append(allowed, method)
}
}
}
if len(allowed) == 0 {
//http.NotFound(w, r)
http.Redirect(w, r, "/error/404", 303)
return
}
w.Header().Add("Allow", strings.Join(allowed, ", "))
//http.Error(w, "Method Not Allowed", 405)
http.Redirect(w, r, "/error/405", 303)
}
示例15: RouteRegex
// routed an regex route
func (d *Dispatcher) RouteRegex(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if length := len(d.Router.RegexRoutes); length == 0 {
return
}
for _, route := range d.Router.RegexRoutes {
//check if Route pattern matches url
if route.regex.MatchString(path) {
//get submatches (params)
matches := route.regex.FindStringSubmatch(path)
//double check that the Route matches the URL pattern.
if len(matches[0]) == len(path) {
if len(route.params) > 0 {
//add url parameters to the query param map
values := r.URL.Query()
for i, match := range matches[1:] {
values.Add(route.params[i], match)
}
//reassemble query params and add to RawQuery
r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
}
parts := strings.Split(route.forward, "/")
d.module, d.controller, d.action = parts[1], parts[2], Util_UCFirst(parts[3])
d.Match(w, r)
break
}
}
}
}