當前位置: 首頁>>代碼示例>>Golang>>正文


Golang url.Values函數代碼示例

本文整理匯總了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,
	})
}
開發者ID:docker,項目名稱:dockercraft,代碼行數:62,代碼來源:image.go

示例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)
}
開發者ID:jonkeller,項目名稱:OAuthExamples,代碼行數:13,代碼來源:authorization_code_grant.go

示例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, ","))
	}
}
開發者ID:peter1000,項目名稱:oanda,代碼行數:14,代碼來源:util.go

示例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, ","))
	}
}
開發者ID:santegoeds,項目名稱:oanda,代碼行數:14,代碼來源:util.go

示例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
}
開發者ID:magisterquis,項目名稱:screepslog,代碼行數:34,代碼來源:auth.go

示例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()
}
開發者ID:shibualexis,項目名稱:go-openid,代碼行數:27,代碼來源:authrequest.go

示例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)
}
開發者ID:yonglehou,項目名稱:go2o,代碼行數:28,代碼來源:member_c.go

示例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()
}
開發者ID:frewsxcv,項目名稱:empire,代碼行數:27,代碼來源:client.go

示例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
}
開發者ID:Patrolavia,項目名稱:apt-mirror-go,代碼行數:29,代碼來源:control_file.go

示例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
	}
}
開發者ID:kapalhq,項目名稱:envoy,代碼行數:34,代碼來源:handler.go

示例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)

}
開發者ID:seven5,項目名稱:seven5,代碼行數:35,代碼來源:raw_test.go

示例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
}
開發者ID:heatxsink,項目名稱:go-foursquare,代碼行數:27,代碼來源:foursquare.go

示例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)
}
開發者ID:hsinhuang,項目名稱:codebase,代碼行數:35,代碼來源:rerouter.go

示例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)
}
開發者ID:scottcagno,項目名稱:netkit,代碼行數:31,代碼來源:mux.go

示例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
			}
		}
	}

}
開發者ID:rainkid,項目名稱:dogo,代碼行數:36,代碼來源:dispatcher.go


注:本文中的net/url.Values函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。