当前位置: 首页>>代码示例>>Golang>>正文


Golang url.ParseQuery函数代码示例

本文整理汇总了Golang中net/url.ParseQuery函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseQuery函数的具体用法?Golang ParseQuery怎么用?Golang ParseQuery使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ParseQuery函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: JWTAuthenticator

/**
 * This is a method for the interface JWTAuthenticator
 * This overrides Handler#ServeHTTP(ResponseWriter, *Request)
 */
func JWTAuthenticator(w http.ResponseWriter, r *http.Request) {

	logger := NewPrefixed("JWTAuthenticator")

	h := md5.New()
	io.WriteString(h, "The fog is getting thicker!")
	io.WriteString(h, "And Leon's getting larger!")
	i := fmt.Sprintf("%x", h.Sum(nil))
	logger.Debug("h.sum() = %v", i)

	logger.Debug("r.Method = %v", r.Method)
	logger.Debug("r.URL = %v", r.URL)
	p, _ := url.ParseQuery(r.URL.Path)
	logger.Debug("ParseQuery(r.URL.Path) = %v", p)
	p, _ = url.ParseQuery(r.URL.RawQuery)
	logger.Debug("ParseQuery(r.URL.RawQuery) = %v", p)
	logger.Debug("len(p['code']) = %v", len(p["code"]))
	logger.Debug("p['code'] = %v", p["code"])
	logger.Debug("r.Header = %v", r.Header)
	logger.Debug("r.Close = %v", r.Close)
	//	logger.Debug("r.Host = %v", r.Host)
	logger.Debug("r.Form = %v", r.Form)
	logger.Debug("len(r.Form) = %v", len(r.Form))
	logger.Debug("r.PostForm = %v", r.PostForm)
	logger.Debug("len(r.PostForm) = %v", len(r.PostForm))
	logger.Debug("r.MultipartForm = %v", r.MultipartForm)
	logger.Debug("r.Trailer = %v", r.Trailer)
	logger.Debug("r.RemoteAddr = %v", r.RemoteAddr)
	logger.Debug("r.RequestURI = %v", r.RequestURI)
	//	logger.Debug("r.TLS = %v", r.TLS)
	for i, v := range r.Form {
		logger.Debug("r.Form[%v] = %v", i, v)
	}
}
开发者ID:sbinet,项目名称:fedid,代码行数:38,代码来源:main.go

示例2: AssertQuery

// AssertQuery verifies the expect HTTP query string matches the actual.
func AssertQuery(t *testing.T, expect, actual string, msgAndArgs ...interface{}) bool {
	expectQ, err := url.ParseQuery(expect)
	if err != nil {
		t.Errorf(errMsg("unable to parse expected Query", err, msgAndArgs))
		return false
	}
	actualQ, err := url.ParseQuery(expect)
	if err != nil {
		t.Errorf(errMsg("unable to parse actual Query", err, msgAndArgs))
		return false
	}

	// Make sure the keys are the same
	if !equal(t, queryValueKeys(expectQ), queryValueKeys(actualQ), msgAndArgs...) {
		return false
	}

	for k, expectQVals := range expectQ {
		sort.Strings(expectQVals)
		actualQVals := actualQ[k]
		sort.Strings(actualQVals)
		equal(t, expectQVals, actualQVals, msgAndArgs...)
	}

	return true
}
开发者ID:ColourboxDevelopment,项目名称:aws-sdk-go,代码行数:27,代码来源:assert.go

示例3: TestURL

func (*storageSuite) TestURL(c *gc.C) {
	container := "container"
	filename := "blobname"
	account := "account"
	key := "bWFkZXlvdWxvb2sK"
	azStorage, _ := makeFakeStorage(container, account, key)
	// Use a realistic service endpoint for this test, so that we can see
	// that we're really getting the expected kind of URL.
	setStorageEndpoint(azStorage, gwacl.GetEndpoint("West US"))
	URL, err := azStorage.URL(filename)
	c.Assert(err, gc.IsNil)
	parsedURL, err := url.Parse(URL)
	c.Assert(err, gc.IsNil)
	c.Check(parsedURL.Host, gc.Matches, fmt.Sprintf("%s.blob.core.windows.net", account))
	c.Check(parsedURL.Path, gc.Matches, fmt.Sprintf("/%s/%s", container, filename))
	values, err := url.ParseQuery(parsedURL.RawQuery)
	c.Assert(err, gc.IsNil)
	signature := values.Get("sig")
	// The query string contains a non-empty signature.
	c.Check(signature, gc.Not(gc.HasLen), 0)
	// The signature is base64-encoded.
	_, err = base64.StdEncoding.DecodeString(signature)
	c.Assert(err, gc.IsNil)
	// If Key is empty, query string does not contain a signature.
	key = ""
	azStorage, _ = makeFakeStorage(container, account, key)
	URL, err = azStorage.URL(filename)
	c.Assert(err, gc.IsNil)
	parsedURL, err = url.Parse(URL)
	c.Assert(err, gc.IsNil)
	values, err = url.ParseQuery(parsedURL.RawQuery)
	c.Assert(err, gc.IsNil)
	c.Check(values.Get("sig"), gc.HasLen, 0)
}
开发者ID:kapilt,项目名称:juju,代码行数:34,代码来源:storage_test.go

示例4: TestEncodeSortedQuery

func TestEncodeSortedQuery(t *testing.T) {
	params, _ := url.ParseQuery("tango=t&bravo=b&juliet=j&charlie=c")
	assertEqual("bravo=b&charlie=c&juliet=j&tango=t", encodeSortedQuery(params), t)
	params, _ = url.ParseQuery("delta=yankee&alpha=foxtrot&delta=alpha&alpha=kilo")
	assertEqual("alpha=foxtrot&alpha=kilo&delta=alpha&delta=yankee", encodeSortedQuery(params), t)
	assertEqual("", encodeSortedQuery(make(map[string][]string)), t)
}
开发者ID:ppone,项目名称:oauth1,代码行数:7,代码来源:access_token_test.go

示例5: parseBody

// Parse Page source for formatlist
func (this *YTVideo) parseBody(body []byte) (map[int]string, error) {

	videoInfo, err := url.ParseQuery(string(body))
	if err != nil {
		return nil, fmt.Errorf("Could not parse video info")
	}

	this.VideoInformation = videoInfo
	this.FormatList = make(map[int]string, 0)

	// Split format list
	for _, v := range strings.Split(videoInfo["url_encoded_fmt_stream_map"][0], ",") {
		formatValues, err := url.ParseQuery(v)
		if err != nil {
			continue
		}

		itag, err := strconv.Atoi(formatValues["itag"][0])
		if err != nil {
			continue
		}

		url := formatValues["url"][0]
		if sig, ok := formatValues["sig"]; ok {
			url += "&signature=" + sig[0]
		}

		// Add video url to result
		this.FormatList[itag] = url
	}

	return this.FormatList, nil
}
开发者ID:Beldur,项目名称:ytdl,代码行数:34,代码来源:ytvideo.go

示例6: ServeHTTP

func (h *TestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if len(h.Requests) <= h.CallCount {
		h.logError("Index out of range! Test server called too many times. Final Request:", r.Method, r.RequestURI)
		return
	}

	tester := h.Requests[h.CallCount]
	h.CallCount++

	// match method
	if tester.Method != r.Method {
		h.logError("Method does not match.\nExpected: %s\nActual:   %s", tester.Method, r.Method)
	}

	// match path
	paths := strings.Split(tester.Path, "?")
	if paths[0] != r.URL.Path {
		h.logError("Path does not match.\nExpected: %s\nActual:   %s", paths[0], r.URL.Path)
	}
	// match query string
	if len(paths) > 1 {
		actualValues, _ := url.ParseQuery(r.URL.RawQuery)
		expectedValues, _ := url.ParseQuery(paths[1])
		if !urlQueryContains(actualValues, expectedValues) {
			h.logError("Query string does not match.\nExpected: %s\nActual:   %s", paths[1], r.URL.RawQuery)
		}
	}

	for key, values := range tester.Header {
		key = http.CanonicalHeaderKey(key)
		actualValues := strings.Join(r.Header[key], ";")
		expectedValues := strings.Join(values, ";")

		if key == "Authorization" && !strings.Contains(actualValues, expectedValues) {
			h.logError("%s header is not contained in actual value.\nExpected: %s\nActual:   %s", key, expectedValues, actualValues)
		}
		if key != "Authorization" && actualValues != expectedValues {
			h.logError("%s header did not match.\nExpected: %s\nActual:   %s", key, expectedValues, actualValues)
		}
	}

	// match custom request matcher
	if tester.Matcher != nil {
		tester.Matcher(r)
	}

	// set response headers
	header := w.Header()
	for name, values := range tester.Response.Header {
		if len(values) < 1 {
			continue
		}
		header.Set(name, values[0])
	}

	// write response
	w.WriteHeader(tester.Response.Status)
	fmt.Fprintln(w, tester.Response.Body)
}
开发者ID:BlueSpice,项目名称:cli,代码行数:59,代码来源:server.go

示例7: TestDomainCreate

func TestDomainCreate(t *testing.T) {
	setup()
	defer teardown()

	respXML := `<?xml version="1.0" encoding="UTF-8"?>
	<ApiResponse xmlns="http://api.namecheap.com/xml.response" Status="OK">
	  <Errors />
	  <RequestedCommand>namecheap.domains.create</RequestedCommand>
	  <CommandResponse Type="namecheap.domains.create">
	    <DomainCreateResult Domain="domain1.com" Registered="true" ChargedAmount="20.3600" DomainID="9007" OrderID="196074" TransactionID="380716" WhoisguardEnable="false" NonRealTimeDomain="false" />
	  </CommandResponse>
	  <Server>SERVER-NAME</Server>
	  <GMTTimeDifference>+5</GMTTimeDifference>
	  <ExecutionTime>0.078</ExecutionTime>
	</ApiResponse>`

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// verify that the URL exactly matches...brittle, I know.
		correctURL := "/?AdminAddress1=8939%20S.cross%20Blvd&ApiUser=anApiUser&ApiKey=anToken&UserName=anUser&Command=namecheap.domains.create&ClientIp=127.0.0.1&DomainName=domain1.com&Years=2&AuxBillingFirstName=John&AuxBillingLastName=Smith&AuxBillingAddress1=8939%20S.cross%20Blvd&AuxBillingStateProvince=CA&AuxBillingPostalCode=90045&AuxBillingCountry=US&AuxBillingPhone=+1.6613102107&[email protected]&AuxBillingCity=CA&TechFirstName=John&TechLastName=Smith&TechAddress1=8939%20S.cross%20Blvd&TechStateProvince=CA&TechPostalCode=90045&TechCountry=US&TechPhone=+1.6613102107&[email protected]&TechCity=CA&AdminFirstName=John&AdminLastName=Smith&AdminStateProvince=CA&AdminPostalCode=90045&AdminCountry=US&AdminPhone=+1.6613102107&[email protected]&AdminCity=CA&RegistrantFirstName=John&RegistrantLastName=Smith&RegistrantAddress1=8939%20S.cross%20Blvd&RegistrantStateProvince=CA&RegistrantPostalCode=90045&RegistrantCountry=US&RegistrantPhone=+1.6613102107&[email protected]&RegistrantCity=CA"
		correctValues, err := url.ParseQuery(correctURL)
		if err != nil {
			t.Fatal(err)
		}
		values, err := url.ParseQuery(r.URL.String())
		if err != nil {
			t.Fatal(err)
		}

		if !reflect.DeepEqual(values, correctValues) {
			t.Fatalf("URL = \n%v,\nwant \n%v", values, correctValues)
		}
		testMethod(t, r, "POST")

		fmt.Fprint(w, respXML)
	})

	client.NewRegistrant(
		"John", "Smith",
		"8939 S.cross Blvd", "",
		"CA", "CA", "90045", "US",
		" 1.6613102107", "[email protected]",
	)

	result, err := client.DomainCreate("domain1.com", 2)
	if err != nil {
		t.Fatalf("DomainCreate returned error: %v", nil)
	}

	// DomainGetListResult we expect, given the respXML above
	want := &DomainCreateResult{
		"domain1.com", true, 20.36, 9007, 196074, 380716, false, false,
	}

	if !reflect.DeepEqual(result, want) {
		t.Fatalf("DomainCreate returned\n%+v,\nwant\n%+v", result, want)
	}
}
开发者ID:cryptickrisp,项目名称:go-namecheap,代码行数:57,代码来源:domain_test.go

示例8: QueryMatches

func (s *scene) QueryMatches(actual string) bool {
	parsed, _ := url.Parse(s.Request.URI)
	expected := parsed.RawQuery
	// either/both strings are empty: no match for you!
	if expected == "" || actual == "" {
		return false
	}
	parsedExpected, _ := url.ParseQuery(expected)
	parsedActual, _ := url.ParseQuery(actual)
	return reflect.DeepEqual(parsedExpected, parsedActual)
}
开发者ID:zeushammer,项目名称:poser,代码行数:11,代码来源:scenes.go

示例9: Setup

// Responsible for doing any necessary setup for each web request.
func (c *App) Setup() revel.Result {
	if args := c.Request.Header.Get("X-Api-Arg"); args != "" {
		m, _ := url.ParseQuery(args)
		c.Client = m.Get("client_id")
		c.Product = m.Get("product")
	}
	if oauth := c.Request.Header.Get("X-Api-Oauth"); oauth != "" {
		m, _ := url.ParseQuery(oauth)
		c.Entid = m.Get("eid")
		c.Sender = m.Get("loginname")
	}

	return nil
}
开发者ID:Rick1125,项目名称:mailgo,代码行数:15,代码来源:app.go

示例10: TestUpdateUser

// Checks if the credentials for the integration tests are set in the env vars
func TestUpdateUser(t *testing.T) {
	setupUserService(t)
	defer tearDownUserService()

	//Our update data
	name := "Chuck"
	surname := "Norris"
	changeFlag := "Changed"

	perfectUser := User{
		FirstName: name,
		LastName:  surname,
	}

	mux.HandleFunc("/user",
		func(w http.ResponseWriter, r *http.Request) {
			testMethod(t, r, "PUT")

			// Convert body to values
			buf := new(bytes.Buffer)
			buf.ReadFrom(r.Body)
			values, _ := url.ParseQuery(buf.String())

			// Get the data
			reqName := values["first_name"][0]
			reqSurname := values["last_name"][0]

			// Check if is the same data and if, seth the flag up
			if reqName != name {
				w.Header().Set("Status", "400 Bad Request")
			} else {
				reqName = reqName + changeFlag
			}

			if reqSurname != surname {
				w.Header().Set("Status", "400 Bad Request")
			} else {
				reqSurname = reqSurname + changeFlag
			}

			fmt.Fprintf(w,
				`{
                  "first_name": "%s",
                  "last_name": "%s"
              }`, reqName, reqSurname)
		},
	)

	userService.Update(&perfectUser)

	if perfectUser.FirstName != name+changeFlag || perfectUser.LastName != surname+changeFlag {
		t.Errorf("Could not update the user")
	}

	// Test bad request
	server.Close()
	if err := userService.Update(&perfectUser); err == nil {
		t.Errorf("No server up, should be an error")
	}
}
开发者ID:bancek,项目名称:go-copy,代码行数:61,代码来源:users_test.go

示例11: handle

func handle(w http.ResponseWriter, r *http.Request) {
	params, err := url.ParseQuery(r.URL.RawQuery)
	check(err)
	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add(
		"Access-Control-Allow-Methods",
		"OPTIONS, HEAD, GET, POST, PUT, DELETE",
	)
	w.Header().Add(
		"Access-Control-Allow-Headers",
		"Content-Type, Content-Range, Content-Disposition",
	)
	switch r.Method {
	case "OPTIONS":
	case "HEAD":
	case "GET":
		get(w, r)
	case "POST":
		if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" {
			delete(w, r)
		} else {
			post(w, r)
		}
	case "DELETE":
		delete(w, r)
	default:
		http.Error(w, "501 Not Implemented", http.StatusNotImplemented)
	}
}
开发者ID:omairrazam,项目名称:bapp,代码行数:29,代码来源:main.go

示例12: main

func main() {
	s := "qvod://user:[email protected]:1234/path?k=v#f"

	fmt.Println("URL:", s)
	u, err := url.Parse(s)
	if err != nil {
		panic(err)
	}

	fmt.Println(u.Scheme)
	fmt.Println(u.User)
	fmt.Println(u.User.Username())
	p, _ := u.User.Password()
	fmt.Println(p)

	fmt.Println(u.Host)
	host, port, _ := net.SplitHostPort(u.Host)
	fmt.Println(host)
	fmt.Println(port)

	fmt.Println(u.Path)
	fmt.Println(u.Fragment)

	fmt.Println(u.RawQuery)
	m, _ := url.ParseQuery(u.RawQuery)
	fmt.Println(m)
	fmt.Println(m["k"][0])
}
开发者ID:datawolf,项目名称:go-study,代码行数:28,代码来源:main.go

示例13: TestDeviceTokenRefresh

func TestDeviceTokenRefresh(t *testing.T) {
	// a test server to represent AGO
	agoServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, r *http.Request) {
		test.Refute(t, r, nil)
		test.Expect(t, r.URL.Path, "/sharing/oauth2/token")
		test.Expect(t, r.Header.Get("Content-Type"), "application/x-www-form-urlencoded")
		contents, _ := ioutil.ReadAll(r.Body)
		test.Refute(t, len(contents), 0)
		vals, _ := url.ParseQuery(string(contents))
		test.Expect(t, len(vals), 4)
		test.Expect(t, vals.Get("client_id"), "good_client_id")
		test.Expect(t, vals.Get("f"), "json")
		test.Expect(t, vals.Get("grant_type"), "refresh_token")
		test.Expect(t, vals.Get("refresh_token"), "good_refresh_token")
		fmt.Fprintln(res, `{"access_token":"refreshed_access_token","expires_in":1800}`)
	}))
	defer agoServer.Close()

	testDevice := &device{
		tokenManager: newTokenManager("old_access_token", "good_refresh_token", 1800),
		clientID:     "good_client_id",
		deviceID:     "device_id",
		env:          testEnv("", agoServer.URL),
	}
	expiresAt := time.Now().Unix() + 1800 - 60

	err := testDevice.refresh("good_refresh_token")
	test.Expect(t, err, nil)
	test.Expect(t, testDevice.getExpiresAt(), expiresAt)
	test.Expect(t, testDevice.getAccessToken(), "refreshed_access_token")
	test.Expect(t, testDevice.clientID, "good_client_id")
	test.Expect(t, testDevice.getRefreshToken(), "good_refresh_token")
}
开发者ID:Esri,项目名称:geotrigger-go,代码行数:33,代码来源:device_test.go

示例14: writeCanonicalizedResource

// From the Amazon docs:
//
// CanonicalizedResource = [ "/" + Bucket ] +
// 	  <HTTP-Request-URI, from the protocol name up to the query string> +
// 	  [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
func writeCanonicalizedResource(buf *bytes.Buffer, req http.Request) {
	// Save request URL.
	requestURL := req.URL
	// Get encoded URL path.
	path := encodeURL2Path(requestURL)
	buf.WriteString(path)

	if requestURL.RawQuery != "" {
		var n int
		vals, _ := url.ParseQuery(requestURL.RawQuery)
		// Verify if any sub resource queries are present, if yes
		// canonicallize them.
		for _, resource := range resourceList {
			if vv, ok := vals[resource]; ok && len(vv) > 0 {
				n++
				// First element
				switch n {
				case 1:
					buf.WriteByte('?')
				// The rest
				default:
					buf.WriteByte('&')
				}
				buf.WriteString(resource)
				// Request parameters
				if len(vv[0]) > 0 {
					buf.WriteByte('=')
					buf.WriteString(strings.Replace(url.QueryEscape(vv[0]), "+", "%20", -1))
				}
			}
		}
	}
}
开发者ID:ptrimble,项目名称:dreamhost-personal-backup,代码行数:38,代码来源:request-signature-v2.go

示例15: GetCustomers

func GetCustomers(ctx *macaron.Context, x *xorm.Engine) {
	m, _ := url.ParseQuery(ctx.Req.URL.RawQuery)
	glog.V(1).Infof("Debug %#v", m)
	skip := 0
	limit := 0
	var err error

	if v, ok := m["skip"]; ok {
		skip, _ = strconv.Atoi(v[0])
	}

	if v, ok := m["limit"]; ok {
		limit, _ = strconv.Atoi(v[0])
	}

	cs := make([]Customer, 0)
	err = x.Limit(limit, skip).Find(&cs)
	if err != nil {
		glog.V(1).Infof("Get customer from db fail:%s", err.Error())
		ctx.JSON(http.StatusInternalServerError, map[string]string{"message": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, cs)
}
开发者ID:renhuiyang,项目名称:macaron_xorm_shoppingweb_practise,代码行数:25,代码来源:customerController.go


注:本文中的net/url.ParseQuery函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。