/** * 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) } }
// 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 }
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) }
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) }
// 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 }
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) }
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", "*****@*****.**", ) 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) } }
// ParseForm parses the raw query from the URL. // // For POST or PUT requests, it also parses the request body as a form. // If the request Body's size has not already been limited by MaxBytesReader, // the size is capped at 10MB. // // ParseMultipartForm calls ParseForm automatically. // It is idempotent. func (r *Request) ParseForm() (err error) { if r.Form != nil { return } if r.URL != nil { r.Form, err = url.ParseQuery(r.URL.RawQuery) } if r.Method == "POST" || r.Method == "PUT" { if r.Body == nil { return errors.New("missing form body") } ct := r.Header.Get("Content-Type") ct, _, err = mime.ParseMediaType(ct) switch { case ct == "application/x-www-form-urlencoded": var reader io.Reader = r.Body maxFormSize := int64(1<<63 - 1) if _, ok := r.Body.(*maxBytesReader); !ok { maxFormSize = int64(10 << 20) // 10 MB is a lot of text. reader = io.LimitReader(r.Body, maxFormSize+1) } b, e := ioutil.ReadAll(reader) if e != nil { if err == nil { err = e } break } if int64(len(b)) > maxFormSize { return errors.New("http: POST too large") } var newValues url.Values newValues, e = url.ParseQuery(string(b)) if err == nil { err = e } if r.Form == nil { r.Form = make(url.Values) } // Copy values into r.Form. TODO: make this smoother. for k, vs := range newValues { for _, value := range vs { r.Form.Add(k, value) } } case ct == "multipart/form-data": // handled by ParseMultipartForm (which is calling us, or should be) // TODO(bradfitz): there are too many possible // orders to call too many functions here. // Clean this up and write more tests. // request_test.go contains the start of this, // in TestRequestMultipartCallOrder. } } return err }
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) }
// 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 }
// 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") } }
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) } }
func main() { s := "qvod://*****:*****@localhost.com: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]) }
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") }
// 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)) } } } } }
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) }
func getValidDeviceClient(t *testing.T) *Client { // 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/registerDevice") 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), 2) test.Expect(t, vals.Get("client_id"), "good_client_id") test.Expect(t, vals.Get("f"), "json") fmt.Fprintln(res, `{"device":{"deviceID":"device_id","client_id":"good_client_id","apnsProdToken":null,"apnsSandboxToken":null,"gcmRegistrationId":null,"registered":1389531528000,"lastAccessed":1389531528000},"deviceToken":{"access_token":"good_access_token","expires_in":1799,"refresh_token":"good_refresh_token"}}`) })) defer agoServer.Close() device := &device{ clientID: "good_client_id", env: testEnv("", agoServer.URL), } err := device.register() test.Expect(t, err, nil) return &Client{device} }
func (s *S) TestEndpointCreate(c *check.C) { config.Set("request-id-header", "Request-ID") h := TestHandler{} ts := httptest.NewServer(&h) defer ts.Close() instance := ServiceInstance{Name: "my-redis", ServiceName: "redis", TeamOwner: "theteam", Description: "xyz"} client := &Client{endpoint: ts.URL, username: "******", password: "******"} err := client.Create(&instance, "my@user", "Request-ID") c.Assert(err, check.IsNil) expectedURL := "/resources" h.Lock() defer h.Unlock() c.Assert(h.url, check.Equals, expectedURL) c.Assert(h.method, check.Equals, "POST") v, err := url.ParseQuery(string(h.body)) c.Assert(err, check.IsNil) c.Assert(map[string][]string(v), check.DeepEquals, map[string][]string{ "name": {"my-redis"}, "user": {"my@user"}, "team": {"theteam"}, "description": {"xyz"}, }) c.Assert("Request-ID", check.Equals, h.request.Header.Get("Request-ID")) c.Assert("application/x-www-form-urlencoded", check.DeepEquals, h.request.Header.Get("Content-Type")) c.Assert("application/json", check.Equals, h.request.Header.Get("Accept")) c.Assert("Basic dXNlcjphYmNkZQ==", check.Equals, h.request.Header.Get("Authorization")) c.Assert("close", check.Equals, h.request.Header.Get("Connection")) }
// Raw stats: Entries from eugo_raw for the last 24 hours // This file is getting a bit long // func rawStats(res http.ResponseWriter, req *http.Request, ps httprouter.Params) { from := func() int64 { urlPS, _ := url.ParseQuery(req.URL.RawQuery) param, ok := urlPS["from"] if ok { ts, err := strconv.ParseInt(param[0], 10, 64) if err == nil { return ts } } return (time.Now().UTC().UnixNano() / 1e6) - 864e5 }() key := ps.ByName("key") rawStats, err := getRawStats(key, from) if err != nil { res.WriteHeader(http.StatusInternalServerError) return } jsonHandler(res, req, rawStats) return }
// SendString returns SuperAgent's itself for any next chain and takes content string as a parameter. // Its duty is to transform String into s.Data (map[string]interface{}) which later changes into appropriate format such as json, form, text, etc. in the End func. // Send implicitly uses SendString and you should use Send instead of this. func (s *SuperAgent) SendString(content string) *SuperAgent { var val map[string]interface{} // check if it is json format d := json.NewDecoder(strings.NewReader(content)) d.UseNumber() if err := d.Decode(&val); err == nil { for k, v := range val { s.Data[k] = v } } else if formVal, err := url.ParseQuery(content); err == nil { for k, _ := range formVal { // make it array if already have key if val, ok := s.Data[k]; ok { var strArray []string strArray = append(strArray, formVal.Get(k)) // check if previous data is one string or array switch oldValue := val.(type) { case []string: strArray = append(strArray, oldValue...) case string: strArray = append(strArray, oldValue) } s.Data[k] = strArray } else { // make it just string if does not already have same key s.Data[k] = formVal.Get(k) } } s.TargetType = "form" } else { // need to add text mode or other format body request to this func } return s }
func (t *Transport) updateToken(tok *Token, v url.Values) error { v.Set("client_id", t.ClientId) v.Set("client_secret", t.ClientSecret) r, err := (&http.Client{Transport: t.transport()}).PostForm(t.TokenURL, v) if err != nil { return err } defer r.Body.Close() if r.StatusCode != 200 { return OAuthError{"updateToken", r.Status} } var b struct { Access string `json:"access_token"` Refresh string `json:"refresh_token"` ExpiresIn time.Duration `json:"expires_in"` Id string `json:"id_token"` } content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) switch content { case "application/x-www-form-urlencoded", "text/plain": body, err := ioutil.ReadAll(r.Body) if err != nil { return err } vals, err := url.ParseQuery(string(body)) if err != nil { return err } b.Access = vals.Get("access_token") b.Refresh = vals.Get("refresh_token") b.ExpiresIn, _ = time.ParseDuration(vals.Get("expires_in") + "s") b.Id = vals.Get("id_token") default: if err = json.NewDecoder(r.Body).Decode(&b); err != nil { return err } // The JSON parser treats the unitless ExpiresIn like 'ns' instead of 's' as above, // so compensate here. b.ExpiresIn *= time.Second } tok.AccessToken = b.Access // Don't overwrite `RefreshToken` with an empty value if len(b.Refresh) > 0 { tok.RefreshToken = b.Refresh } if b.ExpiresIn == 0 { tok.Expiry = time.Time{} } else { tok.Expiry = time.Now().Add(b.ExpiresIn) } if b.Id != "" { if tok.Extra == nil { tok.Extra = make(map[string]string) } tok.Extra["id_token"] = b.Id } return nil }
// 实现 http.Handler func (frontend *MultiServerFrontend) ServeHTTP(w http.ResponseWriter, r *http.Request) { queryValues, err := url.ParseQuery(r.URL.RawQuery) if err != nil { frontend.invalidRequestHandler.ServeInvalidRequest(w, r, err) return } if interceptor := frontend.interceptor; interceptor != nil && !interceptor.Intercept(w, r, queryValues) { return } serverKey := queryValues.Get(URLQueryServerKeyName) if serverKey == "" { err = fmt.Errorf("the url query value with name %s is empty", URLQueryServerKeyName) frontend.invalidRequestHandler.ServeInvalidRequest(w, r, err) return } frontend.rwmutex.RLock() server := frontend.serverMap[serverKey] frontend.rwmutex.RUnlock() if server == nil { err = fmt.Errorf("Not found Server for %s == %s", URLQueryServerKeyName, serverKey) frontend.invalidRequestHandler.ServeInvalidRequest(w, r, err) return } ServeHTTP(w, r, queryValues, server, frontend.invalidRequestHandler) }
// signatureBase combines the uppercase request method, percent encoded base // string URI, and parameter string. Returns the OAuth1 signature base string // according to RFC5849 3.4.1. // Does not mutate the Request or basicOAuthParams. func signatureBase(req *http.Request, basicOAuthParams map[string]string) (string, error) { method := strings.ToUpper(req.Method) baseURL := strings.Split(req.URL.String(), "?")[0] // add oauth, query, and body parameters into params params := map[string]string{} for key, value := range req.URL.Query() { // most backends do not accept duplicate query keys params[key] = value[0] } if req.Body != nil && req.Header.Get(contentType) == formContentType { // reads data to a []byte, draining req.Body b, err := ioutil.ReadAll(req.Body) if err != nil { return "", err } values, err := url.ParseQuery(string(b)) if err != nil { return "", err } for key, value := range values { params[key] = value[0] } // reinitialize Body with ReadCloser over the []byte req.Body = ioutil.NopCloser(bytes.NewReader(b)) } for key, value := range basicOAuthParams { params[key] = value } // encode params into a parameter string (RFC5849 3.4.1.3, 3.4.1.3.2) parameterString := encodeParams(params) baseParts := []string{method, PercentEncode(baseURL), PercentEncode(parameterString)} return strings.Join(baseParts, "&"), nil }
// Dial connect to mongo, and return an error if there's a problem func (t *MongoTarget) Dial() error { username := t.dstURI.User.Username() password, _ := t.dstURI.User.Password() parsedQuery, _ := url.ParseQuery(t.dstURI.RawQuery) servers := strings.Split(t.dstURI.Host, ",") dialInfo := &mgo.DialInfo{ Addrs: servers, Database: t.dstDB, Username: username, Password: password, Timeout: time.Second * time.Duration(*connectionTimeout), } if replicaSet, hasReplicaSet := parsedQuery["replicaSet"]; hasReplicaSet { dialInfo.ReplicaSetName = replicaSet[0] } if ssl, hasSSL := parsedQuery["ssl"]; hasSSL && ssl[0] == "true" { dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) { conn, err := tls.Dial("tcp", addr.String(), &tls.Config{InsecureSkipVerify: *ignoreSslError}) if err != nil { logger.Error("tls err, %v", err) } return conn, err } } session, err := mgo.DialWithInfo(dialInfo) if err != nil { return fmt.Errorf("Cannot dial with dialInfo %v\n, %v", dialInfo, err) } t.dst = session return nil }
func (c *Client) request(client *http.Client, credentials *Credentials, urlStr string, params url.Values) (*Credentials, url.Values, error) { c.SignParam(credentials, "POST", urlStr, params) resp, err := client.PostForm(urlStr, params) if err != nil { return nil, nil, err } p, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return nil, nil, err } if resp.StatusCode != 200 { return nil, nil, fmt.Errorf("OAuth server status %d, %s", resp.StatusCode, string(p)) } vals, err := url.ParseQuery(string(p)) if err != nil { return nil, nil, err } credentials = &Credentials{ Token: vals.Get("oauth_token"), Secret: vals.Get("oauth_token_secret"), } if credentials.Token == "" { return nil, nil, errors.New("No OAuth token in server result") } if credentials.Secret == "" { return nil, nil, errors.New("No OAuth secret in server result") } return credentials, vals, nil }
func (svc *GoPushService) handlePing(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { serve404(w) return } v, _ := url.ParseQuery(r.URL.RawQuery) center := v.Get("center") callback := v.Get("callback") // For JSONP if _, ok := svc.lastState[center]; center == "" || !ok { serve404(w) return } if callback == "" { // Normal response w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) io.WriteString(w, svc.lastState[center]) } else { // JSONP response w.Header().Set("Content-Type", "application/javascript; charset=utf-8") w.WriteHeader(http.StatusOK) marshaled, _ := json.Marshal(svc.lastState[center]) io.WriteString(w, callback+"("+string(marshaled)+");") } }
// ParseForm parses the raw query from the URL and updates r.Form. // // For POST or PUT requests, it also parses the request body as a form and // put the results into both r.PostForm and r.Form. // POST and PUT body parameters take precedence over URL query string values // in r.Form. // // If the request Body's size has not already been limited by MaxBytesReader, // the size is capped at 10MB. // // ParseMultipartForm calls ParseForm automatically. // It is idempotent. func (r *Request) ParseForm() error { var err error if r.PostForm == nil { if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" { r.PostForm, err = parsePostForm(r) } if r.PostForm == nil { r.PostForm = make(url.Values) } } if r.Form == nil { if len(r.PostForm) > 0 { r.Form = make(url.Values) copyValues(r.Form, r.PostForm) } var newValues url.Values if r.URL != nil { var e error newValues, e = url.ParseQuery(r.URL.RawQuery) if err == nil { err = e } } if newValues == nil { newValues = make(url.Values) } if r.Form == nil { r.Form = newValues } else { copyValues(r.Form, newValues) } } return err }
func (rm *RouteManager) AddFromUri(uri string) error { expandedRoute := os.ExpandEnv(uri) u, err := url.Parse(expandedRoute) if err != nil { return err } r := &Route{ Address: u.Host, Adapter: u.Scheme, Options: make(map[string]string), } if u.RawQuery != "" { params, err := url.ParseQuery(u.RawQuery) if err != nil { return err } for key, _ := range params { value := params.Get(key) switch key { case "filter.id": r.FilterID = value case "filter.name": r.FilterName = value case "filter.sources": r.FilterSources = strings.Split(value, ",") default: r.Options[key] = value } } } return rm.Add(r) }
func isolatorStrFromString(is string) (types.ACIdentifier, string, error) { is = "name=" + is v, err := url.ParseQuery(strings.Replace(is, ",", "&", -1)) if err != nil { return "", "", err } var name string var values []string var acn *types.ACIdentifier for key, val := range v { if len(val) > 1 { return "", "", fmt.Errorf("label %s with multiple values %q", key, val) } switch key { case "name": acn, err = types.NewACIdentifier(val[0]) if err != nil { return "", "", err } name = val[0] default: // (TODO)yifan: Not support the default boolean yet. values = append(values, fmt.Sprintf(`"%s": "%s"`, key, val[0])) } } return *acn, getIsolatorStr(name, strings.Join(values, ", ")), nil }
func TestDeviceRegisterFail(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/registerDevice") 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), 2) test.Expect(t, vals.Get("client_id"), "bad_client_id") test.Expect(t, vals.Get("f"), "json") fmt.Fprintln(res, `{"error":{"code":999,"message":"Unable to register device.","details":["'client_id' invalid"]}}`) })) defer agoServer.Close() device := &device{ clientID: "bad_client_id", env: testEnv("", agoServer.URL), } expectedErrorMessage := "Error from /sharing/oauth2/registerDevice, code: 999. Message: Unable to register device." err := device.register() test.Refute(t, err, nil) test.Expect(t, err.Error(), expectedErrorMessage) }