示例#1
0
func (ts *Tribserver) GetSubscriptions(args *tribproto.GetSubscriptionsArgs, reply *tribproto.GetSubscriptionsReply) os.Error {
	//check if user exists
	suscribersJson, stat, err := ts.tm.GET(args.Userid + SUBSCRIPTIONS)
	if err != nil {
		return err
	}
	if stat == storageproto.OK {
		subscribers := make(map[string]bool)
		err := json.Unmarshal(suscribersJson, &subscribers)
		if err != nil {
			return err
		}
		reply.Userids = make([]string, len(subscribers))
		i := 0

		//add each userid in the suscribers list to the reply arg
		for key, _ := range subscribers {
			s := new(string)
			err = json.Unmarshal([]byte(key), s)
			if err != nil {
				return err
			}
			reply.Userids[i] = *s
			i++
		}
		reply.Status = tribproto.OK
	} else {
		reply.Status = tribproto.ENOSUCHUSER
	}
	return nil
}
示例#2
0
func TestJsonCodec(t *testing.T) {
	m1 := []byte(`{"site":"xxx", "dep":[], "op":{"$t":[ "Hello World", {"$s":5}, {"$d":3} ] } }`)

	mut, err := DecodeMutation(m1)
	if err != nil {
		t.Fatal(err.String())
		return
	}
	m1b, _, err := EncodeMutation(mut, EncNormal)
	if err != nil {
		t.Fatal(err.String())
		return
	}

	d1 := make(map[string]interface{})
	d2 := make(map[string]interface{})
	err = json.Unmarshal(m1, &d1)
	if err != nil {
		t.Fatal(err.String())
		return
	}
	err = json.Unmarshal(m1b, &d2)
	if err != nil {
		t.Fatal(err.String())
		return
	}

	if !compareJson(d1, d2) {
		t.Fatalf("Decoding and Encoding changed the mutation content:\n%v\n%v\n", string(m1), string(m1b))
		return
	}
}
示例#3
0
func (s *S) TestObjectIdJSONUnmarshalingError(c *C) {
	v := jsonType{}
	err := json.Unmarshal([]byte(`{"Id":"4d88e15b60f486e428412dc9A"}`), &v)
	c.Assert(err, Matches, `Invalid ObjectId in JSON: "4d88e15b60f486e428412dc9A"`)
	err = json.Unmarshal([]byte(`{"Id":"4d88e15b60f486e428412dcZ"}`), &v)
	c.Assert(err, Matches, `Invalid ObjectId in JSON: "4d88e15b60f486e428412dcZ" \(invalid hex char: 90\)`)
}
示例#4
0
/*
json.Unmarshal wrapper
extracts json data into new interface and returns populated array of interfaces and any errors raised
*/
func (this *Neo4j) unmarshal(s string) (dataSet map[int]*NeoTemplate, err os.Error) {
	var (
		templateNode map[string]interface{}   // blank interface for json.Unmarshal; used for node lvl data
		templateSet  []map[string]interface{} // array of blank interfaces for json.Unmarshal
	)
	dataSet = make(map[int]*NeoTemplate)           // make it ready for elements
	err = json.Unmarshal([]byte(s), &templateNode) // unmarshal json data into blank interface. the json pkg will populate with the proper data types
	if err != nil {                                // fails on multiple results
		err = json.Unmarshal([]byte(s), &templateSet) // if unable to unmarshal into single template, try an array of templates instead. If that fails, raise an error
		if err != nil {
			return nil, err
		}
		for _, v := range templateSet {
			data, err := this.unmarshalNode(v) // append NeoTemplate into the data set
			if err != nil {
				return nil, err
			}
			dataSet[len(dataSet)] = data // new array element containing data
		}
	} else {
		template, err := this.unmarshalNode(templateNode)
		if err != nil {
			return nil, err
		}
		dataSet[0] = template // just a single result
	}
	return
}
示例#5
0
func TestJsonCodec2(t *testing.T) {
	m1 := []byte(`{"site":"xxx", "dep":["abc"], "op":{"$t":[ "Hello World", {"$s":5}, {"$d":3} ] } }`)
	var mut Mutation
	err := json.Unmarshal(m1, &mut)
	if err != nil {
		t.Fatal(err.String())
		return
	}
	if mut.Site != "xxx" || mut.Operation.Kind != StringOp || mut.Dependencies[0] != "abc" {
		t.Fatal("Decoding failed")
	}
	m1b, err := json.Marshal(&mut)
	if err != nil {
		t.Fatal(err.String())
		return
	}

	d1 := make(map[string]interface{})
	d2 := make(map[string]interface{})
	err = json.Unmarshal(m1, &d1)
	if err != nil {
		t.Fatal(err.String())
		return
	}
	err = json.Unmarshal(m1b, &d2)
	if err != nil {
		t.Fatal(err.String())
		return
	}

	if !compareJson(d1, d2) {
		t.Fatalf("Decoding and Encoding changed the mutation content:\n%v\n%v\n", string(m1), string(m1b))
		return
	}
}
示例#6
0
func testJsonGet(server *Server, uri string, jsonResponse string, t *testing.T) bool {
	// Send a POST message to create a document
	u, ok := NewURI(uri)
	if !ok {
		t.Errorf("Failed to parse URI")
		return false
	}
	ch := make(chan bool)
	w := NewResponseWriter()
	req := &GetRequest{Request{w, "", ch, ClientOrigin, u}}
	server.Get(req)
	<-ch
	if w.StatusCode != 200 {
		t.Errorf("Expected status code 200")
		return false
	}

	j1 := make(map[string]interface{})
	if err := json.Unmarshal(w.Buffer.Bytes(), &j1); err != nil {
		t.Errorf("Failed to parse JSON response: %v", err)
		return false
	}
	j2 := make(map[string]interface{})
	if err := json.Unmarshal([]byte(jsonResponse), &j2); err != nil {
		t.Errorf("Malformed JSON in test case: %v\n", jsonResponse, err)
		return false
	}
	if !compareJson(j1, j2) {
		t.Errorf("Expected\n\t%v\ninstead got\n\t%v\n", jsonResponse, string(w.Buffer.Bytes()))
		return false
	}
	return true
}
示例#7
0
func TestOT(t *testing.T) {
	text1 := "{\"_rev\":0, \"_data\":{\"$object\":true, \"abc\":\"xyz\", \"num\": 123, \"foo\":{\"$object\":true, \"a\":1,\"b\":3}, \"arr\":{\"$array\":[1,2,3]}}}"
	dest1 := make(map[string]interface{})
	err := json.Unmarshal([]byte(text1), &dest1)
	if err != nil {
		t.Errorf("Cannot parse: %v", err)
		return
	}

	text2 := "{\"_rev\":0, \"_data\":{\"$object\":true, \"torben\":\"weis\", \"num\": 321, \"foo\":{\"$object\":true, \"a\":6,\"c\":33}, \"arr\":{\"$array\":[4,5,6]}}}"
	dest2 := make(map[string]interface{})
	err = json.Unmarshal([]byte(text2), &dest2)
	if err != nil {
		t.Errorf("Cannot parse: %v", err)
		return
	}

	m1 := DocumentMutation(dest1)
	m2 := DocumentMutation(dest2)
	var ot Transformer
	err = ot.Transform(m1, m2)
	if err != nil {
		t.Errorf("Cannot transform: %v", err)
		return
	}

	enc1, _ := json.Marshal(dest1)
	log.Println("t1=", string(enc1))
	enc2, _ := json.Marshal(dest2)
	log.Println("t2=", string(enc2))
}
示例#8
0
func main() {
	// Read the string
	inputReader := bufio.NewReader(os.Stdin)

	var info = Metadata{"", uint32(0), nil}
	var cmd = Command{"", nil, nil, nil, ""}

	infoJson, err := inputReader.ReadString('\n')
	if err != nil {
		log.Exit(err)
	} else {
		json.Unmarshal(infoJson, &info)
	}

	bpt, bperr := bptree.NewBpTree(info.Filename, info.Keysize, info.Fieldsizes)
	if !bperr {
		log.Exit("Failed B+ tree creation")
	} else {
		fmt.Println("ok")
	}

	alive := true

	for alive {
		cmdJson, err := inputReader.ReadString('\n')
		if err != nil {
			alive = false
			break
		}
		if cmdJson == "q\n" {
			alive = false
		} else {
			json.Unmarshal(cmdJson, &cmd)
			if cmd.Op == "insert" {
				result := bpt.Insert(cmd.LeftKey, cmd.Fields)
				fmt.Println(result)
			} else if cmd.Op == "find" {
				records, ack := bpt.Find(cmd.LeftKey, cmd.RightKey)
				for record := range records {
					json.Marshal(os.Stdout, map[string]interface{}{
						"key":   record.GetKey(),
						"value": record.AllFields()})
					fmt.Println()
					ack <- true
				}
				fmt.Println("end")
			} else if cmd.Op == "visualize" {
				bptree.Dotty(cmd.FileName, bpt)
			} else if cmd.Op == "prettyprint" {
				s := fmt.Sprintln(bpt)
				f, _ := os.Open(cmd.FileName, os.O_RDWR|os.O_CREAT, 0666)
				f.Write([]byte(s))
				f.Close()
			}
		}
	}
	fmt.Println("exited")
}
示例#9
0
func TestCreateUserAccount(t *testing.T) {
	ds := inmemory.NewInMemoryDataStore()
	wm := webmachine.NewWebMachine()
	wm.AddRouteHandler(account.NewCreateAccountRequestHandler(ds, ds))
	buf := bytes.NewBufferString(`{"role": 9999999999999999, "name": "George Washington", "username": "******", "email":"*****@*****.**", "phone_number": "+1-405-555-5555", "address": "Valley Forge"}`)
	oldUser := new(dm.User)
	json.Unmarshal(buf.Bytes(), &oldUser)
	req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/account/user/create/", buf)
	req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
	req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
	req.Header.Set("Accept-Charset", "utf-8")
	req.Header.Set("Accept-Encoding", "identity")
	req.Header.Set("Accept-Language", "en-us")
	req.Header.Set("Connection", "close")
	resp := webmachine.NewMockResponseWriter(req)
	wm.ServeHTTP(resp, req)
	if resp.StatusCode != 200 {
		t.Error("Expected 200 status code but received ", resp.StatusCode)
	}
	if resp.Header().Get("Content-Type") != req.Header.Get("Accept") {
		t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type"))
	}
	user := new(dm.User)
	obj := jsonhelper.NewJSONObject()
	err := json.Unmarshal(resp.Buffer.Bytes(), &obj)
	user.InitFromJSONObject(obj.GetAsObject("result"))
	if err != nil {
		t.Error("Error while unmarshaling JSON: ", err.String())
	}
	if obj.GetAsString("status") != "success" {
		t.Error("Expected status = \"success\", but was \"", obj.GetAsString("status"), "\"")
	}
	if user.Name != oldUser.Name {
		t.Error("Expected name = \"", oldUser.Name, "\", but was ", user.Name)
	}
	if user.Username != oldUser.Username {
		t.Error("Expected username = \"", oldUser.Username, "\", but was ", user.Username)
	}
	if user.Email != oldUser.Email {
		t.Error("Expected email = \"", oldUser.Email, "\", but was ", user.Email)
	}
	if user.PhoneNumber != oldUser.PhoneNumber {
		t.Error("Expected phone_number = \"", oldUser.PhoneNumber, "\", but was ", user.PhoneNumber)
	}
	if user.Address != oldUser.Address {
		t.Error("Expected address = \"", oldUser.Address, "\", but was ", user.Address)
	}
	if user.Role != dm.ROLE_STANDARD {
		t.Error("Expected role = ", dm.ROLE_STANDARD, " but was ", user.Role)
	}
	if user.Id == "" {
		t.Error("Expected id to be populated, but was empty")
	}
}
示例#10
0
func TestUpdateDocument(t *testing.T) {
    initDatabase(t)
    doc := map[string]string{"a": "12", "b": "this is a test"}

    database := NewDatabase("http://127.0.0.1:5984/test123/")
    docid, revid, err := database.Create(tojs(doc))

    if err != nil {
        t.Error(err.String())
    }

    if docid == "" {
        t.Error("Doc Id is null")
    }

    contents := map[string]string{}

    data, err := database.Get(docid)
    if err != nil {
        t.Error(err.String())
    }

    json.Unmarshal(data, &contents)

    if contents["a"] != "12" || contents["b"] != "this is a test" {
        t.Error("parameter mismatch")
    }

    contents["a"] = "100"
    contents["b"] = "this is a test 2"
    contents["_id"] = docid
    contents["_rev"] = revid

    err = database.Update(docid, tojs(contents))

    if err != nil {
        t.Error(err.String())
    }

    data, err = database.Get(docid)
    if err != nil {
        t.Error(err.String())
    }

    json.Unmarshal(data, &contents)

    if contents["a"] != "100" || contents["b"] != "this is a test 2" {
        t.Error("parameter mismatch")
    }

}
示例#11
0
func getParams(req *jsonRequest, argTypes []reflect.Type) ([]reflect.Value, os.Error) {
	params := make([]*json.RawMessage, 0)
	err := json.Unmarshal(*req.Params, &params)

	if err != nil {
		return nil, err
	}

	if len(params) != len(argTypes) {
		return nil, os.ErrorString("Incorrect number of parameters.")
	}

	args := make([]reflect.Value, 0, len(argTypes))

	for i, argType := range argTypes {
		argPointerType := argType

		if argPointerType.Kind() == reflect.Ptr {
			argPointer := reflect.New(argType)
			err := json.Unmarshal(*params[i], argPointer.Interface())
			if err != nil {
				return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
			}
			args = append(args, reflect.Indirect(argPointer))
		} else {
			var arg reflect.Value
			var v interface{}
			err := json.Unmarshal(*params[i], &v)
			if err != nil {
				return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
			}
			value := reflect.ValueOf(v)
			if value.Type() == argType {
				arg = reflect.ValueOf(v)
			} else if value.Type().Kind() == reflect.Float32 || value.Type().Kind() == reflect.Float64 {
				if argType.Kind() == reflect.Int || argType.Kind() == reflect.Int8 ||
					argType.Kind() == reflect.Int16 || argType.Kind() == reflect.Int32 ||
					argType.Kind() == reflect.Int64 {
					arg = reflect.ValueOf(int(v.(float64)))
				} else {
					return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
				}
			} else {
				return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
			}
			args = append(args, reflect.Value(arg))
		}
	}
	return args, nil
}
示例#12
0
func fetchFacebookStatuses(c appengine.Context) ([]Status, os.Error) {
	graph_url := "https://graph.facebook.com/" + config.Username + "/statuses" + "?limit=1000&access_token=" + config.AccessToken
	client := urlfetch.Client(c)
	response, err := client.Get(graph_url)

	if err != nil {
		c.Errorf("Error fetching item from facebook, %s.\nResponse.", err.String())
		return nil, err
	}

	data, readErr := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if readErr != nil {
		c.Errorf("Error reading bytes from response, %s", readErr)
		return nil, readErr
	}

	var m StatusList
	jsonErr := json.Unmarshal(data, &m)
	if jsonErr != nil {
		c.Errorf("Error unmarshalling json from facebook, %s", jsonErr)
		return nil, jsonErr
	}
	return m.Data, nil
}
示例#13
0
文件: config.go 项目: abneptis/GoAWS
func (self *proxyConf) UnmarshalJSON(in []byte) (err os.Error) {
	confmap := map[string]string{}
	err = json.Unmarshal(in, &confmap)
	if err == nil {
		if _, ok := confmap["Bucket"]; !ok {
			return os.NewError("Bucket is required")
		}
		self.Prefix = confmap["Prefix"]
		if self.Prefix == "" {
			self.Prefix = "/"
		}
		self.Bucket = s3.NewBucket(&http.URL{
			Scheme: "http",
			Host:   "s3.amazonaws.com",
			Path:   self.Prefix,
		}, confmap["Bucket"], nil)

		if confmap["AccessKey"] != "" && confmap["SecretKey"] != "" {
			self.Identity = aws.NewSigner(confmap["AccessKey"], confmap["SecretKey"])
		} else {
			self.Identity, err = DefaultSigner()
		}
	}
	return
}
示例#14
0
func handleInviteByMail(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	_, _, err := getSession(c, r)
	if err != nil {
		sendError(w, r, "No session cookie")
		return
	}

	blob, err := ioutil.ReadAll(r.Body)
	if err != nil {
		sendError(w, r, "Error reading request body")
		return
	}
	r.Body.Close()

	var req inviteByMail
	err = json.Unmarshal(blob, &req)
	if err != nil {
		sendError(w, r, "Malformed request body: "+err.String())
		return
	}

	msg := &mail.Message{
		Sender:  "*****@*****.**",
		To:      []string{req.UserName},
		Subject: "Invitation to LightWave",
		Body:    req.Content,
	}
	if err := mail.Send(c, msg); err != nil {
		sendError(w, r, "Could not send mail")
		c.Errorf("Couldn't send email: %v", err)
	}
}
示例#15
0
func (p *Parameters) Load(filename string) {
	buf, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Panicf("Parameter Readfile %s error %v", filename, err)
	}
	json.Unmarshal(buf, &p)
}
示例#16
0
// Project like Expand above.
// But this will return with short URL's analytics as a
// map[string]interface{} type.
func (req *Googl) Project(url, proj string) (map[string]interface{}, os.Error) {
	proj = strings.ToUpper(proj)
	if "FULL" != proj && "ANALYTICS_CLICKS" != proj && "ANALYTICS_TOP_STRINGS" != proj {
		return nil, os.EINVAL
	}

	res, err := req.get(url, map[string]string{"projection": proj})
	if err != nil {
		return nil, err
	}

	var temp map[string]interface{}
	if err = json.Unmarshal([]byte(res), &temp); err != nil {
		return nil, os.Error(err)
	}

	if _, ok := temp["code"]; ok {
		msg, _ := temp["message"].(string)

		return nil, os.NewError(msg)
	}

	if status, _ := temp["status"]; "OK" != status {
		msg, _ := status.(string)

		return nil, os.NewError(msg)
	}

	return temp, nil
}
示例#17
0
// getConfig return string map of configuration that store email and password.
func getConfig() (config map[string]string) {
	file := ""
	if syscall.OS == "windows" {
		file = filepath.Join(os.Getenv("USERPROFILE"), "Application Data", "goissue", "settings.json")
	} else {
		file = filepath.Join(os.Getenv("HOME"), ".config", "goissue", "settings.json")
	}

	b, err := ioutil.ReadFile(file)
	if err != nil {
		log.Fatal("failed to read file "+file+":", err)
	}
	err = json.Unmarshal(b, &config)
	if err != nil {
		log.Fatal("failed to unmarhal settings.json:", err)
	}

	if _, ok := config["email"]; !ok {
		log.Fatal("failed to get email from your settings.json:", err)
	}
	if _, ok := config["password"]; !ok {
		log.Fatal("failed to get email from your settings.json:", err)
	}
	if _, ok := config["project"]; ok {
		project = config["project"]
	}
	return config
}
示例#18
0
文件: bitly.go 项目: thevermi/rbot
func shorten(long string) (short string) {
	key := "R_e659dbb5514e34edc3540a7c95b0041b"
	login := "******"

	long = url.QueryEscape(long)

	url_ := fmt.Sprintf("http://api.bit.ly/v3/shorten?login=%s&apiKey=%s&longUrl=%s&format=json", login, key, long)
	r, err := http.Get(url_)
	defer r.Body.Close()

	if err != nil {
		return "Error connecting to bit.ly"
	}

	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return "Error reading bit.ly response"
	}

	var j map[string]interface{}

	err = json.Unmarshal(b, &j)
	if err != nil {
		return "Unable to shorten URL."
	}

	var data map[string]interface{} = j["data"].(map[string]interface{})

	return data["url"].(string)
}
func Call(address string, method string, id interface{}, params []interface{}) (map[string]interface{}, os.Error) {
	data, err := json.Marshal(map[string]interface{}{
		"method": method,
		"id":     id,
		"params": params,
	})
	if err != nil {
		log.Fatalf("Marshal: %v", err)
		return nil, err
	}
	resp, err := http.Post(address,
		"application/json", strings.NewReader(string(data)))
	if err != nil {
		log.Fatalf("Post: %v", err)
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("ReadAll: %v", err)
		return nil, err
	}
	result := make(map[string]interface{})
	err = json.Unmarshal(body, &result)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
		return nil, err
	}
	//log.Println(result)
	return result, nil
}
示例#20
0
func AppEngineVerify(r *http.Request) string {

	if err := r.ParseForm(); err != nil {
		return "Anonymous"
	}

	token := r.FormValue("assertion")
	url := "https://browserid.org/verify"
	bodytype := "application/x-www-form-urlencoded"
	body := strings.NewReader("assertion=" + token + "&audience=" + r.Host)

	var response_body []byte
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	res, err := client.Post(url, bodytype, body)
	if err != nil {
		fmt.Println("err=", err)
		return "Anonymous"
	} else {
		response_body, _ = ioutil.ReadAll(res.Body)
		res.Body.Close()
	}

	var f interface{}
	json.Unmarshal(response_body, &f)

	m := f.(map[string]interface{})
	return fmt.Sprintf("%s", m["email"])
}
示例#21
0
// Expand expands a shortened url to long url.
// It returns the orgin url and nil if success, or empty string
// and an os.Error when failed.
func (req *Googl) Expand(url string) (string, os.Error) {
	res, err := req.get(url)
	if err != nil {
		return "", err
	}

	var temp map[string]string
	if err = json.Unmarshal([]byte(res), &temp); err != nil {
		return "", os.Error(err)
	}

	if _, ok := temp["code"]; ok {
		return "", os.NewError(temp["message"])
	}

	if status, _ := temp["status"]; "OK" != status {
		return "", os.NewError(status)
	}

	url, ok := temp["longUrl"]
	if !ok {
		return "", os.NewError("Invalid response")
	}

	return url, nil
}
示例#22
0
func TestMapCounter(t *testing.T) {
	colours := NewMap("bike-shed-colours")

	colours.Add("red", 1)
	colours.Add("red", 2)
	colours.Add("blue", 4)
	if x := colours.m["red"].(*Int).i; x != 3 {
		t.Errorf("colours.m[\"red\"] = %v, want 3", x)
	}
	if x := colours.m["blue"].(*Int).i; x != 4 {
		t.Errorf("colours.m[\"blue\"] = %v, want 4", x)
	}

	// colours.String() should be '{"red":3, "blue":4}',
	// though the order of red and blue could vary.
	s := colours.String()
	var j interface{}
	err := json.Unmarshal([]byte(s), &j)
	if err != nil {
		t.Errorf("colours.String() isn't valid JSON: %v", err)
	}
	m, ok := j.(map[string]interface{})
	if !ok {
		t.Error("colours.String() didn't produce a map.")
	}
	red := m["red"]
	x, ok := red.(float64)
	if !ok {
		t.Error("red.Kind() is not a number.")
	}
	if x != 3 {
		t.Errorf("red = %v, want 3", x)
	}
}
示例#23
0
func (ss *Storageserver) GetListRPC(args *storageproto.GetArgs, reply *storageproto.GetListReply) os.Error {
	reply.Lease = storageproto.LeaseStruct{}

	reply.Lease.Granted = false
	reply.Lease.ValidSeconds = 0
	if args.WantLease && ss.handleLeaseRequest(args) { // grant the lease if possible
		reply.Lease.Granted = true
		reply.Lease.ValidSeconds = LEASE_SECONDS
	}

	val, status := ss.tm.GET(args.Key)
	reply.Status = status
	if status == storageproto.OK {
		set := make(map[string]bool)
		err := json.Unmarshal(val, &set)
		if err != nil {
			reply.Status = storageproto.EPUTFAILED
		} else {
			reply.Value = make([]string, len(set))
			i := 0
			for key, _ := range set {
				reply.Value[i] = key
				i++
			}
		}
	}
	return nil
}
示例#24
0
func (c *Client) RetweetedOfMe(sinceId uint64, maxId uint64, count uint, page uint) (t []Tweet) {
	var params string
	var tweets []Tweet

	if sinceId != 0 {
		params = addParam(params, "since_id", fmt.Sprintf("%d", sinceId))
	}
	if maxId != 0 {
		params = addParam(params, "max_id", fmt.Sprintf("%d", maxId))
	}
	if count != 0 {
		params = addParam(params, "count", fmt.Sprintf("%d", count))
	}
	if page != 0 {
		params = addParam(params, "page", fmt.Sprintf("%d", page))
	}

	url := c.makeAuthURL(retweetedOfMe, params)
	res, _, err := http.Get(url)
	if err != nil {
		return nil
	}

	if res.Status != "200 OK" {
		return nil
	}

	reader := bufio.NewReader(res.Body)
	line, _ := reader.ReadString(0)

	json.Unmarshal(line, &tweets)

	return tweets
}
示例#25
0
func TestCreateDocument(t *testing.T) {
    initDatabase(t)

    test_document := struct {
        a   int
        b   string
    }{12, "this is a test"}

    database := NewDatabase("http://127.0.0.1:5984/test123/")

    docid, _, err := database.Create(tojs(test_document))
    if err != nil {
        t.Error(err.String())
    }

    if docid == "" {
        t.Error("Doc Id is null")
    }

    var contents struct {
        A   int
        B   string
    }

    data, err := database.Get(docid)

    if err != nil {
        t.Error(err.String())
    }
    json.Unmarshal(data, &contents)
    if contents.A != 12 || contents.B != "this is a test" {
        t.Error("parameter mismatch")
    }

}
示例#26
0
func (c *Client) StatusesRetweets(id uint64, count int) (t []Tweet) {
	var params string
	var tweets []Tweet

	if id == 0 {
		return nil
	}

	if count != 0 {
		params = addParam(params, "count", fmt.Sprintf("%d", count))
	}

	url := c.makeAuthURL(statusesRetweets+fmt.Sprintf("/%d", id), params)
	res, _, err := http.Get(url)
	if err != nil {
		return nil
	}

	if res.Status != "200 OK" {
		return nil
	}

	reader := bufio.NewReader(res.Body)
	line, _ := reader.ReadString(0)

	print(line + "\n")
	json.Unmarshal(line, &tweets)

	return tweets
}
示例#27
0
func listenForMoveRequests(conn *net.TCPConn) {
	listenServe := make(chan []uint8)
	easynet.TieConnToChannel(conn, listenServe)
	for data := range listenServe {
		r := new(ttypes.BotMoveRequest)
		err := json.Unmarshal(data, r)
		easynet.DieIfError(err, "JSON error")

		if r.Kill {
			fmt.Printf("Bot on %s received kill signal\n", os.Args[0])
			os.Exit(0)
		}

		fmt.Printf("Bot at %d, %d received messages: %v\n", r.YourX, r.YourY, r.Messages)
		fmt.Printf("  Sees other bots: %v\n", r.OtherBots)
		//Do something

		response := new(ttypes.BotMoveResponse)
		if r.YourY < 5 {
			response.MoveDirection = "up"
		} else if r.YourY > 5 {
			response.MoveDirection = "down"
		}
		// response.BroadcastMessage = fmt.Sprintf("'I am %v at %d, %d'", os.Args[0], r.YourX, r.YourY)
		responseString, err := json.Marshal(response)
		easynet.DieIfError(err, "JSON marshal error")
		conn.Write(responseString)
	}
}
示例#28
0
func (c *Client) StatusesFollowers(userId uint64, screenName string, cursor int) (u []User) {
	var params string
	var users []User

	if userId != 0 {
		params = addParam(params, "user_id", fmt.Sprintf("%d", userId))
	}
	if screenName != "" {
		params = addParam(params, "screen_name", screenName)
	}
	if cursor != 0 {
		params = addParam(params, "cursor", fmt.Sprintf("%d", cursor))
	}

	url := c.makeAuthURL(statusesFollowers, params)
	res, _, err := http.Get(url)
	if err != nil {
		return nil
	}

	if res.Status != "200 OK" {
		return nil
	}

	reader := bufio.NewReader(res.Body)
	line, _ := reader.ReadString(0)

	json.Unmarshal(line, &users)

	return users

}
示例#29
0
func HandleRequest(request []byte, pubCallback func([]byte, int), callbackKey int) {
	var requestObj PlaylistRequest
	var response []byte

	err := json.Unmarshal(request, &requestObj)
	if err != nil {
		log.Panicf("Error parsing JSON: %s", err.String())
	}

	switch requestObj.Action {
	case ACTION_ADD:
		callbackKey = -1
		response = AddTrackToPlaylist(requestObj.Target)
	case ACTION_REMOVE:
		callbackKey = -1
		response = RemoveTrackFromPlaylist(requestObj.Target.Key)
	case ACTION_REORDER:
		response = []byte("Reorder track in playlist")
	case ACTION_GET:
		response = GetPlaylist()
	default:
		response = []byte("Couldn't figure out action: " + requestObj.Action)
	}

	response = GetPlaylist()
	go pubCallback(response, callbackKey)
}
示例#30
0
func (t *Twitter) getTimeline(url string) (out string, err os.Error) {
	var r *http.Response
	r, err = http_auth.Get(url, t.Account.Username, t.Account.Password)

	if err != nil {
		return
	}

	if r.StatusCode != 200 {
		err = os.ErrorString("Twitter returned: " + r.Status)
		return
	}

	b, _ := ioutil.ReadAll(r.Body)
	r.Body.Close()

	tweets := make([]Tweet, 20)
	json.Unmarshal(string(b), tweets)

	re, _ := regexp.Compile("<a[^>]*>(.*)</a>")
	for _, t := range tweets {
		// Source may be a link: <a href="...">source</a>
		// Extract text of the link with regexp.
		matches := re.MatchStrings(t.Source)
		if matches != nil && len(matches) > 0 {
			t.Source = matches[1]
		}

		if t.Text != "" {
			out = out + fmt.Sprintf("%v: %v (%v)\n\n", t.User.Screen_name,
				t.Text, t.Source)
		}
	}
	return
}