Esempio n. 1
0
func TestApiCreateEvent_400(t *testing.T) {
	var genParams = func(omitName string) url.Values {
		params := url.Values{
			"title":      []string{"test tour title"},
			"link":       []string{"http://www.example.com/"},
			"image_link": []string{"http://www.example.com/img.png"},
		}
		params.Del(omitName)
		return params
	}

	test.RunTestServer(func(ts *test.TestServer) {
		assert := test.NewAssert(t)
		test.DatastoreFixture(ts.Context, "./fixtures/TestApiCreateEventShow.json", nil)
		p := app.TestApp().Api.Path("/events/")
		var testOmitParams = []string{
			"title", "link", "image_link",
		}
		for _, paramName := range testOmitParams {
			req := ts.PostForm(p, genParams(paramName))
			lib.SetApiTokenForTest(req, lib.Admin)
			res := req.RouteTo(app.TestApp().Routes())
			assert.HttpStatus(400, res)
		}
	})
}
Esempio n. 2
0
// Ensures that a key could update TTL.
//
//   $ curl -X PUT localhost:4001/v2/keys/foo -d value=XXX
//   $ curl -X PUT localhost:4001/v2/keys/foo -d value=XXX -d ttl=1000 -d prevExist=true
//   $ curl -X PUT localhost:4001/v2/keys/foo -d value=XXX -d ttl= -d prevExist=true
//
func TestV2UpdateKeySuccessWithTTL(t *testing.T) {
	tests.RunServer(func(s *server.Server) {
		v := url.Values{}
		v.Set("value", "XXX")
		resp, _ := tests.PutForm(fmt.Sprintf("%s%s", s.URL(), "/v2/keys/foo"), v)
		assert.Equal(t, resp.StatusCode, http.StatusCreated)
		node := (tests.ReadBodyJSON(resp)["node"]).(map[string]interface{})
		createdIndex := node["createdIndex"]

		v.Set("ttl", "1000")
		v.Set("prevExist", "true")
		resp, _ = tests.PutForm(fmt.Sprintf("%s%s", s.URL(), "/v2/keys/foo"), v)
		assert.Equal(t, resp.StatusCode, http.StatusOK)
		node = (tests.ReadBodyJSON(resp)["node"]).(map[string]interface{})
		assert.Equal(t, node["value"], "XXX", "")
		assert.Equal(t, node["ttl"], 1000, "")
		assert.NotEqual(t, node["expiration"], "", "")
		assert.Equal(t, node["createdIndex"], createdIndex, "")

		v.Del("ttl")
		resp, _ = tests.PutForm(fmt.Sprintf("%s%s", s.URL(), "/v2/keys/foo"), v)
		assert.Equal(t, resp.StatusCode, http.StatusOK)
		node = (tests.ReadBodyJSON(resp)["node"]).(map[string]interface{})
		assert.Equal(t, node["value"], "XXX", "")
		assert.Equal(t, node["ttl"], nil, "")
		assert.Equal(t, node["expiration"], nil, "")
		assert.Equal(t, node["createdIndex"], createdIndex, "")
	})
}
Esempio n. 3
0
func (ph *patHandler) Path(values ...url.Values) string {
	// TODO refactor to build string in place or from preprocessed parts

	// find captures
	var i int
	captures := make([]string, 0)
	for i < len(ph.pat) {
		switch {
		default:
			i++
		case ph.pat[i] == ':':
			var name string
			name, _, i = match(ph.pat, isAlnum, i+1)
			captures = append(captures, name)
		}
	}

	// setup url values
	v := url.Values{}
	if len(values) > 0 {
		v = values[0]
	}
	path := ph.pat
	for _, capture := range captures {
		first := v.Get(capture)
		path = strings.Replace(path, ":"+capture, first, -1)
		v.Del(capture)
	}
	if query := v.Encode(); len(query) > 0 {
		path += strings.Join([]string{"?", query}, "")
	}
	return path
}
Esempio n. 4
0
func (c *testCustomizer) EditValues(m url.Values) {
	for k := range m {
		if k == "b" {
			m.Del(k)
		}
	}
}
Esempio n. 5
0
// SetValue modifies the values.
func (ep EnumParam) SetValue(values url.Values, pname string, uinter enums.Uinter) (string, *bool) {
	this := uinter.Touint()
	_, low, err := uinter.Marshal()
	if err != nil { // ignoring the error
		return "", nil
	}

	text := ep.EnumDecodec.Text(strings.ToUpper(low))
	ddef := ep.EnumDecodec.Default.Uint
	dnum := ep.Number

	// Default ordering is desc (values are numeric most of the time).
	// Alpha values ordering: asc.
	desc := !ep.IsAlpha(this)
	if dnum.Negative {
		desc = !desc
	}
	var ret *bool
	if this == dnum.Uint {
		ret = new(bool)
		*ret = !desc
	}
	// for default, opposite of having a parameter is it's absence.
	if this == ddef && ep.Specified {
		values.Del(pname)
		return text, ret
	}
	if this == dnum.Uint && !dnum.Negative && !ep.EnumDecodec.OnlyPositive {
		low = "-" + low
	}
	values.Set(pname, low)
	return text, ret
}
Esempio n. 6
0
// GetMessagesInRange gets an Iterator containing calls in the range [start,
// end), optionally further filtered by data. GetMessagesInRange panics if
// start is not before end. Any date filters provided in data will be ignored.
// If you have an end, but don't want to specify a start, use twilio.Epoch for
// start. If you have a start, but don't want to specify an end, use
// twilio.HeatDeath for end.
//
// Assumes that Twilio returns resources in chronological order, latest
// first. If this assumption is incorrect, your results will not be correct.
//
// Returned MessagePages will have at most PageSize results, but may have
// fewer, based on filtering.
func (c *MessageService) GetMessagesInRange(start time.Time, end time.Time, data url.Values) MessagePageIterator {
	if start.After(end) {
		panic("start date is after end date")
	}
	d := url.Values{}
	if data != nil {
		for k, v := range data {
			d[k] = v
		}
	}
	d.Del("DateSent")
	d.Del("Page") // just in case
	// Omit these parameters if they are the sentinel values, since I think
	// that API paging will be faster.
	if start != Epoch {
		startFormat := start.UTC().Format(APISearchLayout)
		d.Set("DateSent>", startFormat)
	}
	if end != HeatDeath {
		// If you specify "DateSent<=YYYY-MM-DD", the *latest* result returned
		// will be midnight (the earliest possible second) on DD. We want all of
		// the results for DD so we need to specify DD+1 in the API.
		//
		// TODO validate midnight-instant math more closely, since I don't think
		// Twilio returns the correct results for that instant.
		endFormat := end.UTC().Add(24 * time.Hour).Format(APISearchLayout)
		d.Set("DateSent<", endFormat)
	}
	iter := NewPageIterator(c.client, d, messagesPathPart)
	return &messageDateIterator{
		start: start,
		end:   end,
		p:     iter,
	}
}
Esempio n. 7
0
func Test_NutrientReport(t *testing.T) {

	nutrientsIDs := []string{"204", "205", "208", "269"}
	v := url.Values{}
	v.Set("max", "12")

	//All foods
	_, err := api.GetNutrientReport(nutrientsIDs, v)
	if err != nil {
		t.Fatal(err)
	}

	//For food groups Dairy and Egg Products (id = 0100) and Poultry Products (id=0500)
	v.Add("fg", "0100")
	v.Add("fg", "0500")
	_, err = api.GetNutrientReport(nutrientsIDs, v)
	if err != nil {
		t.Fatal(err)
	}

	v.Del("fg")

	//For chedder cheese (ndbno 01009) only:
	v.Set("ndbno", "01009")
	_, err = api.GetNutrientReport(nutrientsIDs, v)
	if err != nil {
		t.Fatal(err)
	}
}
Esempio n. 8
0
// GetCallsInRange gets an Iterator containing calls in the range [start, end),
// optionally further filtered by data. GetCallsInRange panics if start is not
// before end. Any date filters provided in data will be ignored. If you have
// an end, but don't want to specify a start, use twilio.Epoch for start. If
// you have a start, but don't want to specify an end, use twilio.HeatDeath for
// end.
//
// Assumes that Twilio returns resources in chronological order, latest
// first. If this assumption is incorrect, your results will not be correct.
//
// Returned CallPages will have at most PageSize results, but may have fewer,
// based on filtering.
func (c *CallService) GetCallsInRange(start time.Time, end time.Time, data url.Values) CallPageIterator {
	if start.After(end) {
		panic("start date is after end date")
	}
	d := url.Values{}
	if data != nil {
		for k, v := range data {
			d[k] = v
		}
	}
	d.Del("StartTime")
	d.Del("Page") // just in case
	if start != Epoch {
		startFormat := start.UTC().Format(APISearchLayout)
		d.Set("StartTime>", startFormat)
	}
	if end != HeatDeath {
		// If you specify "StartTime<=YYYY-MM-DD", the *latest* result returned
		// will be midnight (the earliest possible second) on DD. We want all
		// of the results for DD so we need to specify DD+1 in the API.
		//
		// TODO validate midnight-instant math more closely, since I don't think
		// Twilio returns the correct results for that instant.
		endFormat := end.UTC().Add(24 * time.Hour).Format(APISearchLayout)
		d.Set("StartTime<", endFormat)
	}
	iter := NewPageIterator(c.client, d, callsPathPart)
	return &callDateIterator{
		start: start,
		end:   end,
		p:     iter,
	}
}
Esempio n. 9
0
func TestApiCreateEventShow_400(t *testing.T) {
	var genParams = func(omitName string) url.Values {
		params := url.Values{
			"open_at":    []string{"2015-01-02T06:00:00Z"},
			"start_at":   []string{"2015-01-02T07:00:00Z"},
			"latitude":   []string{"37.39"},
			"longitude":  []string{"140.38"},
			"venue_id":   []string{"153237058036933"},
			"venue_name": []string{"郡山市民文化センター"},
			"pia_link":   []string{"http://pia.jp/link"},
			"ya_keyword": []string{"郡山"},
		}
		params.Del(omitName)
		return params
	}

	test.RunTestServer(func(ts *test.TestServer) {
		assert := test.NewAssert(t)
		test.DatastoreFixture(ts.Context, "./fixtures/TestApiCreateEventShow.json", nil)
		p := app.TestApp().Api.Path("/events/event1/shows")
		var testOmitParams = []string{
			"open_at", "start_at", "latitude", "longitude", "venue_id", "venue_name", // "pia_link", "ya_keyword",
		}
		for _, paramName := range testOmitParams {
			req := ts.PostForm(p, genParams(paramName))
			lib.SetApiTokenForTest(req, lib.Admin)
			res := req.RouteTo(app.TestApp().Routes())
			assert.HttpStatus(400, res)
		}
	})
}
Esempio n. 10
0
// collectParameters collects parameters from the request.
//
// See RFC 5849 Section 3.4.1.3.1.
func collectParameters(req *http.Request, extra url.Values) (url.Values, error) {
	params, err := parseAuthorizationHeader(req)
	if err != nil {
		return nil, err
	}

	rv := url.Values{}
	err = req.ParseForm()
	if err == nil {
		for k := range req.Form {
			for _, v := range req.Form[k] {
				rv.Add(k, v)
			}
		}
	}

	for k := range params {
		for _, v := range params[k] {
			rv.Add(k, v)
		}
	}

	for k := range extra {
		for _, v := range extra[k] {
			rv.Add(k, v)
		}
	}

	rv.Del("oauth_signature")

	return rv, nil
}
Esempio n. 11
0
// ChangeYear changes the yeargroup filtered by the query
func changeYear(query url.Values, year string) string {

	if _, exists := query["year"]; exists {
		query.Del("year")
	}
	query.Add("year", year)
	return query.Encode()
}
Esempio n. 12
0
// Feed the changes.
//
// The handler receives the body of the stream and is expected to consume
// the contents.
func (p Database) Changes(handler ChangeHandler,
	options map[string]interface{}) error {

	largest := i64defopt(options, "since", 0)

	heartbeatTime := i64defopt(options, "heartbeat", 5000)

	timeout := time.Minute
	if heartbeatTime > 0 {
		timeout = time.Millisecond * time.Duration(heartbeatTime*2)
	}

	for largest >= 0 {
		params := url.Values{}
		for k, v := range options {
			params.Set(k, fmt.Sprintf("%v", v))
		}
		if largest > 0 {
			params.Set("since", fmt.Sprintf("%v", largest))
		}

		if heartbeatTime > 0 {
			params.Set("heartbeat", fmt.Sprintf("%d", heartbeatTime))
		} else {
			params.Del("heartbeat")
		}

		full_url := fmt.Sprintf("%s/_changes?%s", p.DBURL(),
			params.Encode())

		var conn net.Conn

		// Swapping out the transport to work around a bug.
		client := &http.Client{Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			Dial: func(n, addr string) (net.Conn, error) {
				var err error
				conn, err = net.Dial(n, addr)
				return conn, err
			},
		}}

		resp, err := client.Get(full_url)
		if err == nil {
			func() {
				defer resp.Body.Close()
				defer conn.Close()

				tc := timeoutClient{resp.Body, conn, timeout}
				largest = handler(&tc)
			}()
		} else {
			log.Printf("Error in stream: %v", err)
			time.Sleep(time.Second * 1)
		}
	}
	return nil
}
Esempio n. 13
0
func normalizeKeys(v url.Values, normalFunc func(string) string) {
	for param, values := range v {
		normalizedParam := normalFunc(param)
		v.Del(param)
		// Mapserv doesn't take multiple values per param
		//  Save a little time and only set the first one
		v.Set(normalizedParam, values[0])
	}
}
Esempio n. 14
0
func GenerateDotString(res []struct {
	ANAME   string
	BNAME   string
	AID     int
	BID     int
	RELKIND string
	RELID   int
	URLS    []string
}, attrs url.Values) string {
	attrs.Del("url")
	attrs.Del("r")

	// split our slice in a slice with only nodes and a slice with only rels
	var splitAt int
	for index, row := range res {
		if row.BNAME != "" {
			splitAt = index
			break
		}
	}

	graphName := "nodes"
	g := gographviz.NewGraph()
	g.SetName(graphName)
	g.SetDir(true)
	g.AddAttr(graphName, "size", "\"15,1000\"")
	g.AddAttr(graphName, "ratio", "compress")
	for k := range attrs {
		g.AddAttr(graphName, k, attrs.Get(k))
	}

	// add nodes
	for _, row := range res[:splitAt] {
		g.AddNode(graphName, strconv.Itoa(row.AID), map[string]string{
			"id":       strconv.Itoa(row.AID),
			"label":    nodeTable(row.ANAME, row.URLS),
			"shape":    "box",
			"fontname": "Verdana",
			"fontsize": "9",
		})
	}

	// add edges
	for _, row := range res[splitAt:] {
		g.AddEdge(strconv.Itoa(row.AID), strconv.Itoa(row.BID), true, map[string]string{
			"id":       strconv.Itoa(row.RELID),
			"label":    row.RELKIND,
			"dir":      relationshipDir(row.RELKIND),
			"tooltip":  row.RELKIND,
			"fontname": "Verdana",
			"fontsize": "9",
		})
	}

	return g.String()
}
Esempio n. 15
0
// QuerySet modifies the values.
func (bp BoolParam) QuerySet(values url.Values, value bool) {
	if values == nil {
		values = bp.Query.Values
	}
	if value == bp.BoolDecodec.Default {
		values.Del(bp.BoolDecodec.Pname)
	} else {
		values.Set(bp.BoolDecodec.Pname, "")
	}
}
Esempio n. 16
0
/*
	Search is used for retrieving records for a domain. It accepts the following
	GET params:

	+ duuid 	- uuid of domain
	+ domain	- string of domain
	+ name		- string of name

*/
func Search(w http.ResponseWriter, r *http.Request, params url.Values, limit, offset int) {
	query := db.SELECT
	var where []string
	var args []interface{}
	i := 1
	for k, _ := range params {
		switch k {
		case "name":
			where = append(where, fmt.Sprintf(k+" = $%d", i))
			args = append(args, params.Get(k))
			i++
		case "duuid", "domain":
			where = append(where, fmt.Sprintf("domain = $%d", i))
			args = append(args, params.Get(k))
			v := params.Get(k)
			params.Del("duuid")
			params.Del("domain")
			params.Set("domain", v)
			i++
		}
	}
	if len(where) > 0 {
		query += "WHERE " + strings.Join(where, " AND ") + " "
	}
	query += fmt.Sprintf("ORDER BY added DESC LIMIT $%d OFFSET $%d", len(args)+1, len(args)+2)
	args = append(args, limit, offset)
	log.Info("Query: " + query)
	log.Info("Args: %+v", args)
	recordList, err := db.GetList(query, args...)
	if err != nil {
		util.Error(err, w)
		return
	}
	// check for none sql errors
	// if we have no results dispatch a worker to get one
	if len(recordList) == 0 {
		// no domain lets grab one using what we assume is a duuid
		log.Info("no records")
		if duuid := params.Get("domain"); duuid != "" {
			log.Info("duuid: " + duuid)
			domain, err := domains.GetByUUID(duuid).One()
			if err != nil {
				log.Info("herererere")
				util.Error(err, w)
				return
			}
			results := <-dispatcher.AddDomain(domain)
			log.Info("%v", results)
			for _, result := range results {
				recordList = append(recordList, result)
			}
		}
	}
	util.ToJSON(cleanParserFromRecords(recordList), err, w)
}
Esempio n. 17
0
func RequestSignatureBaseString(method string, absUrl string, params url.Values) string {
	params.Del("oauth_signature")

	var paramsArr sort.StringSlice
	for key, _ := range params {
		paramsArr = append(paramsArr, fmt.Sprintf("%s=%s", percentEncode(key), percentEncode(params.Get(key))))
	}

	sort.Sort(paramsArr)
	paramString := strings.Join(paramsArr, "&")
	return method + "&" + percentEncode(absUrl) + "&" + percentEncode(paramString)
}
Esempio n. 18
0
// apple pay 验证签名
func VerifyApplepaySign(publicKey *rsa.PublicKey, values url.Values) error {
	// rsa verify
	sign := values.Get("signature")
	values.Del("signature")
	value := strings.Join(GetKeysAndValuesBySortKeys(values), "&")
	s, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		log.Println(err)
		return err
	}
	return rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, Sha1(value), s)
}
Esempio n. 19
0
func TestRestoreTransferList(t *testing.T) {
	if runRestTests(t) == false {
		return
	}
	client := getClient(t)
	resp := client.RestoreTransferList(nil)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)
	assert.NotEmpty(t, resp.RestoreTransfers())
	assert.False(t, resp.Count == 0)

	totalRecordCount := resp.Count

	params := url.Values{}
	params.Set("bag_valid", "true")
	resp = client.RestoreTransferList(params)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)

	params.Set("bag_valid", "false")
	resp = client.RestoreTransferList(params)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)

	params.Del("bag_valid")
	params.Set("fixity_accept", "true")
	resp = client.RestoreTransferList(params)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)

	params.Set("fixity_accept", "false")
	resp = client.RestoreTransferList(params)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)

	params.Del("fixity_accept")

	aLongTimeAgo := time.Date(1999, time.December, 31, 23, 0, 0, 0, time.UTC)
	params.Set("after", aLongTimeAgo.Format(time.RFC3339Nano))
	resp = client.RestoreTransferList(params)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)
	assert.Equal(t, totalRecordCount, resp.Count)

	params.Set("after", time.Now().Add(1*time.Hour).Format(time.RFC3339Nano))
	resp = client.RestoreTransferList(params)
	require.NotNil(t, resp)
	require.Nil(t, resp.Error)
	assert.EqualValues(t, 0, resp.Count)
	assert.Empty(t, resp.RestoreTransfers())
}
Esempio n. 20
0
File: service.go Progetto: ncw/GoAWS
func (self *Service) ListDomains(id *aws.Signer) (out []string, err error) {
	var resp *http.Response
	parms := url.Values{}
	parms.Set("Action", "ListDomains")
	parms.Set("MaxNumberOfDomains", "100")
	var done bool
	nextToken := ""
	for err == nil && !done {
		xmlresp := listdomainsresponse{}
		if nextToken != "" {
			parms.Set("NextToken", nextToken)
		} else {
			parms.Del("NextToken")
		}
		req := aws.NewRequest(self.URL, "GET", nil, parms)

		err = id.SignRequestV2(req, aws.Canonicalize, DEFAULT_API_VERSION, 0)
		if err == nil {
			resp, err = self.conn.Request(req)
		}

		if err == nil {
			resp, err = self.conn.Request(req)
		}
		if err == nil {
			defer resp.Body.Close()
			if resp.StatusCode != http.StatusOK {
				err = errors.New("Unexpected response")
				ob, _ := httputil.DumpResponse(resp, true)
				os.Stdout.Write(ob)
			}
			if err == nil {
				err = xml.NewDecoder(resp.Body).Decode(&xmlresp)
				if err == nil {
					if xmlresp.ErrorCode != "" {
						err = errors.New(xmlresp.ErrorCode)
					}
					if err == nil {
						for d := range xmlresp.Domains {
							out = append(out, xmlresp.Domains[d])
						}
					}
					nextToken = xmlresp.NextToken
				}
			}
		}
		done = (nextToken == "")
	}
	return
}
Esempio n. 21
0
func (c *Consumer) headers(method string, url string, values url.Values, secret string) map[string]string {
	signature := c.sign(method, url, values, secret)
	var headers []string
	for k, v := range values {
		if strings.HasPrefix(k, "oauth") {
			headers = append(headers, encodeQuoted(k, v[0]))
			values.Del(k)
		}
	}
	headers = append(headers, encodeQuoted("oauth_signature", signature))
	sort.Strings(headers)
	return map[string]string{
		"Authorization": "OAuth " + strings.Join(headers, ", "),
	}
}
Esempio n. 22
0
// ali pay 验证签名
func VerifyAlipaySign(publicKey *rsa.PublicKey, values url.Values) error {
	// rsa verify
	sign := values.Get("sign")
	values.Del("sign")
	values.Del("sign_type")
	value := strings.Join(GetKeysAndValuesBySortKeys(values), "&")
	s, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		return err
	}
	h := sha1.New()
	h.Write([]byte(value))
	digest := h.Sum(nil)
	return rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, digest, s)
}
Esempio n. 23
0
func (la Linkattrs) _attr(base url.Values, seq SEQ) *bool {
	unlessreverse := func(t bool) *bool {
		if la.Bimap.SEQ2REVERSE[seq] {
			t = !t
		}
		return &t
	}

	if la.Pname == "" {
		if seq == la.Bimap.Default_seq {
			return unlessreverse(false)
		}
		return nil
	}

	seqstring := la.Bimap.SEQ2STRING[seq]
	values, have_param := base[la.Pname]
	base.Set(la.Pname, seqstring)

	if !have_param { // no parameter in url
		if seq == la.Bimap.Default_seq {
			return unlessreverse(false)
		}
		return nil
	}

	pos, neg := values[0], values[0]
	if neg[0] == '-' {
		pos = neg[1:]
		neg = neg[1:]
	} else {
		neg = "-" + neg
	}

	var ascr *bool
	if pos == seqstring {
		t := neg[0] != '-'
		if seq == la.Bimap.Default_seq {
			t = true
		}
		ascr = unlessreverse(t)
		base.Set(la.Pname, neg)
	}
	if seq == la.Bimap.Default_seq {
		base.Del(la.Pname)
	}
	return ascr
}
Esempio n. 24
0
func TestFilter_Request(t *testing.T) {
	print("Filter_Request\n")
	c := gsc(t)
	gl, err := c.Games()
	assert.Nil(t, err, "c.Games()")
	r := http.Request{}
	uv := url.Values{}
	uv.Add("dummy", "dummy")
	r.Form = uv
	assert.Equal(t, len(Filter(gl).Request(&r)), 801, "FilterRequest()")
	uv.Add("has", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(has=true)")
	uv.Del("has")
	uv.Add("manual", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(manual=true)")
	uv.Del("manual")
	uv.Add("box", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(box=true)")
}
Esempio n. 25
0
func isEqual(v, u url.Values) bool {
	for key, value := range v {
		if len(u[key]) == 0 {
			return false
		}
		sort.Strings(value)
		sort.Strings(u[key])
		for i := range value {
			if value[i] != u[key][i] {
				return false
			}
		}
		u.Del(key)
	}
	if len(u) > 0 {
		return false
	}
	return true
}
Esempio n. 26
0
// Get IMDBID from TMDB (yes)
func getTMDBDetails(film string, messages chan TMDBFilm) {
	// Let's check if we this in cache
	TmdbFilm := make(chan TMDBFilm)
	foundInCache := make(chan bool)

	go getTMDBCacheFilm(film, TmdbFilm, foundInCache)

	if <-foundInCache {
		cachedFilm := <-TmdbFilm
		messages <- cachedFilm
	} else {
		search := url.Values{}
		search.Set("api_key", conf.TMDB.ApiKey)
		search.Add("query", film)
		result := struct {
			Page         int    `json:"page"`
			Results      []Film `json:"results"`
			TotalPages   int    `json:"total_page"`
			TotalResults int    `json:"total_results"`
		}{}

		getRESTResponse(conf.TMDB.URL, &search, &result)

		Trace.Printf("Title : %s [%s]", result.Results[0].Title, result.Results[0].ReleaseDate)
		Trace.Println("Note : ", result.Results[0].VoteAverage)
		search.Del("query")
		// Create TMDB URL
		var buffer bytes.Buffer
		buffer.WriteString(fmt.Sprint(conf.TMDB.MovieURL, "/", result.Results[0].Id))

		movieURL := buffer.String()
		var resultDetail TMDBFilm
		getRESTResponse(movieURL, &search, &resultDetail)
		done := make(chan struct{})
		go cacheTMDBFilm(resultDetail, done)
		Trace.Printf("%v\n", resultDetail)
		<-done
		messages <- resultDetail
	}

}
Esempio n. 27
0
/*
CheckParams checks that all q.Required params are present in v and if not returns an err.
Checks that there are no addtional params (beyond q.Required and q.Optional) and if
so returns an err.
*/
func (q *Query) CheckParams(v url.Values) (err error) {
	if q.Required != nil {
		var missing []string

		for k, _ := range q.Required {
			if v.Get(k) == "" {
				missing = append(missing, k)

			}
		}

		switch len(missing) {
		case 0:
		case 1:
			err = fmt.Errorf("missing query parameter: " + missing[0])
			return
		default:
			err = fmt.Errorf("missing query parameters: " + strings.Join(missing, ", "))
			return
		}

		for k, _ := range q.Required {
			v.Del(k)
		}

	}

	if q.Optional != nil {
		for k, _ := range q.Optional {
			v.Del(k)
		}
	}

	if len(v) > 0 {
		err = fmt.Errorf("incorrect number of query params.")
	}

	return
}
Esempio n. 28
0
func handleFormData(c *Client, r *Request) {
	formData := url.Values{}

	for k, v := range c.FormData {
		for _, iv := range v {
			formData.Add(k, iv)
		}
	}

	for k, v := range r.FormData {
		// remove form data field from client level by key
		// since overrides happens for that key in the request
		formData.Del(k)

		for _, iv := range v {
			formData.Add(k, iv)
		}
	}

	r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode()))
	r.Header.Set(hdrContentTypeKey, formContentType)
	r.isFormData = true
}
Esempio n. 29
0
func parseURLStringAndToken(path string, method string, params url.Values) (string, string) {
	var token string

	u, err := url.ParseRequestURI(host)
	if err != nil {
		return "", ""
	}

	params.Set("format", "json")
	// If token is present in params, then take it out set as a header
	if token = params.Get("Authorization"); token != "" {
		params.Del("Authorization")
	}

	u.Path = path

	if method == "GET" {
		u.RawQuery = params.Encode()
	}
	urlStr := fmt.Sprintf("%v", u)

	return urlStr, token
}
Esempio n. 30
0
func computeOAuthSignature(method, urlString string, parameters url.Values, secret string) string {
	// method must be upper case
	method = strings.ToUpper(method)

	// make sure scheme and host are lower case
	u, err := url.Parse(urlString)
	if err != nil {
		log.Printf("Error parsing URI: %v", err)
		return ""
	}
	u.Scheme = strings.ToLower(u.Scheme)
	u.Opaque = ""
	u.User = nil
	u.Host = strings.ToLower(u.Host)
	u.RawQuery = ""
	u.Fragment = ""
	reqURL := u.String()

	// get a sorted list of parameter keys (minus oauth_signature)
	oldsig := parameters.Get("oauth_signature")
	parameters.Del("oauth_signature")
	params := encode(parameters)
	if oldsig != "" {
		parameters.Set("oauth_signature", oldsig)
	}

	// get the full string
	s := escape(method) + "&" + escape(reqURL) + "&" + escape(params)

	// perform the signature
	// key is a combination of consumer secret and token secret, but we don't have token secrets
	mac := hmac.New(sha1.New, []byte(escape(secret)+"&"))
	mac.Write([]byte(s))
	sum := mac.Sum(nil)

	return base64.StdEncoding.EncodeToString(sum)
}