func TestGetCard(t *testing.T) {
	//create new records
	res, err := rt.Table("card").Insert(newCard).Run(Session)
	if err != nil {
		panic(err.Error())
	}
	var result response
	res.One(&result)

	req, _ := http.NewRequest("GET",
		fmt.Sprintf("/api/v1/cards/%v", result.GeneratedKeys[0]), nil)

	w := httptest.NewRecorder()

	r.ServeHTTP(w, req)

	if w.Code != 200 {
		t.Errorf("expected %v but got %v", http.StatusOK, w.Code)
		return
	}

	var cardRes Card
	err = json.Unmarshal(w.Body.Bytes(), &cardRes)
	if err != nil {
		t.Error(err.Error())
	}

	if cardRes.CardId != newCard.CardId {
		t.Errorf("Expected CardId %v but got %v", newCard.CardId, cardRes.CardId)
		return
	}
}
示例#2
0
func (r *Rethinkdb) sendAllDocuments(table string) error {
	if r.debug {
		fmt.Printf("sending all documents for %s\n", table)
	}

	cursor, err := gorethink.Table(table).Run(r.client)
	if err != nil {
		return err
	}
	defer cursor.Close()

	var doc map[string]interface{}
	for cursor.Next(&doc) {
		if stop := r.pipe.Stopped; stop {
			return nil
		}

		msg := message.NewMsg(message.Insert, r.prepareDocument(doc), r.computeNamespace(table))
		r.pipe.Send(msg)
	}

	if err := cursor.Err(); err != nil {
		return err
	}

	return nil
}
示例#3
0
// DeleteClient deletes given client
func (s *RethinkDBStorage) DeleteClient(c osin.Client) error {
	result, err := r.Table(clientsTable).Filter(r.Row.Field("Id").Eq(c.GetId())).Run(s.session)
	if err != nil {
		return err
	}
	defer result.Close()

	var clientMap map[string]interface{}
	err = result.One(&clientMap)
	if err != nil {
		return err
	}

	_, err = r.Table(clientsTable).Get(clientMap["id"]).Delete().RunWrite(s.session)
	return err
}
示例#4
0
func main() {
	fmt.Println("Connecting to RethinkDB")

	session, err := r.Connect(r.ConnectOpts{
		Address:  "localhost:7704",
		Database: "players",
	})

	session.SetMaxOpenConns(10)

	if err != nil {
		log.Fatal("Could not connect")
	}

	fmt.Println("Loop through updates")
	for {
		pl := rand.Intn(10000)
		sc := rand.Intn(6) - 2

		// startingTime := time.Now()
		_, err = r.Table("scores").Get(strconv.Itoa(pl)).Update(map[string]interface{}{
			"Score": r.Row.Field("Score").Add(sc),
		}).RunWrite(session)
		// fmt.Println(time.Now().Sub(startingTime))

		time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
	}
}
示例#5
0
// LoadAuthorize gets authorization data with given code
func (s *RethinkDBStorage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
	result, err := r.Table(authorizeTable).Filter(r.Row.Field("Code").Eq(code)).Run(s.session)
	if err != nil {
		return nil, err
	}
	defer result.Close()

	var dataMap map[string]interface{}
	err = result.One(&dataMap)
	if err != nil {
		return nil, err
	}

	var client osin.Client
	clientID := dataMap["Client"].(map[string]interface{})["Id"].(string)
	client, err = s.GetClient(clientID)
	if err != nil {
		return nil, err
	}
	dataMap["Client"] = client

	var dataStruct osin.AuthorizeData
	err = mapstructure.Decode(dataMap, &dataStruct)
	if err != nil {
		return nil, err
	}

	return &dataStruct, nil
}
示例#6
0
// Start the adaptor as a source
func (r *Rethinkdb) Start() error {
	if r.debug {
		fmt.Printf("getting a changes cursor\n")
	}

	// Grab a changes cursor before sending all rows. The server will buffer
	// changes while we reindex the entire table.
	var ccursor *gorethink.Cursor
	ccursor, err := gorethink.Table(r.table).Changes().Run(r.client)
	if err != nil {
		r.pipe.Err <- err
		return err
	}
	defer ccursor.Close()

	if err := r.sendAllDocuments(); err != nil {
		r.pipe.Err <- err
		return err
	}

	if r.tail {
		if err := r.sendChanges(ccursor); err != nil {
			r.pipe.Err <- err
			return err
		}
	}

	return nil
}
示例#7
0
// removeAccessData is a common function to remove AccessData by field
func (s *RethinkDBStorage) removeAccessData(fieldName, token string) error {
	result, err := r.Table(accessTable).Filter(r.Row.Field(fieldName).Eq(token)).Run(s.session)
	if err != nil {
		return err
	}
	defer result.Close()

	var dataMap map[string]interface{}
	err = result.One(&dataMap)
	if err != nil {
		return err
	}

	_, err = r.Table(accessTable).Get(dataMap["id"]).Delete().RunWrite(s.session)
	return err
}
示例#8
0
func postCard(rw http.ResponseWriter, req *http.Request) {

	// parse body
	jsonData, _ := ioutil.ReadAll(req.Body)
	var newCard Card
	err := json.Unmarshal(jsonData, &newCard)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		return
	}
	cursor, err := rt.Table("card").Insert(newCard).Run(Session)
	if err != nil {
		log.Println(err.Error())
		return
	}

	var res interface{}
	err = cursor.One(&res)
	if err != nil {
		fmt.Print(err)
		return
	}

	rw.WriteHeader(http.StatusCreated)
}
示例#9
0
// RemoveAuthorize deletes given authorization
func (s *RethinkDBStorage) RemoveAuthorize(code string) error {
	result, err := r.Table(authorizeTable).Filter(r.Row.Field("Code").Eq(code)).Run(s.session)
	if err != nil {
		return err
	}
	defer result.Close()

	var dataMap map[string]interface{}
	err = result.One(&dataMap)
	if err != nil {
		return err
	}

	_, err = r.Table(authorizeTable).Get(dataMap["id"]).Delete().RunWrite(s.session)
	return err
}
示例#10
0
文件: post.go 项目: esiqveland/den
func (self *RethinkPosting) Create(post Posting) (string, error) {
	wr, err := r.Table(postingsTable).Insert(&post).RunWrite(self.session)
	if err != nil {
		return "", err
	}
	log.Printf("%v", wr.GeneratedKeys)
	return wr.GeneratedKeys[0], nil
}
示例#11
0
// applyOp applies one operation to the database
func (r *Rethinkdb) applyOp(msg *message.Msg) (*message.Msg, error) {
	var (
		resp gorethink.WriteResponse
		err  error
	)

	_, msgTable, err := msg.SplitNamespace()
	if err != nil {
		r.pipe.Err <- NewError(ERROR, r.path, fmt.Sprintf("rethinkdb error (msg namespace improperly formatted, must be database.table, got %s)", msg.Namespace), msg.Data)
		return msg, nil
	}
	if !msg.IsMap() {
		r.pipe.Err <- NewError(ERROR, r.path, "rethinkdb error (document must be a json document)", msg.Data)
		return msg, nil
	}
	doc := msg.Map()

	switch msg.Op {
	case message.Delete:
		id, err := msg.IDString("id")
		if err != nil {
			r.pipe.Err <- NewError(ERROR, r.path, "rethinkdb error (cannot delete an object with a nil id)", msg.Data)
			return msg, nil
		}
		resp, err = gorethink.Table(msgTable).Get(id).Delete().RunWrite(r.client)
	case message.Insert:
		resp, err = gorethink.Table(msgTable).Insert(doc).RunWrite(r.client)
	case message.Update:
		resp, err = gorethink.Table(msgTable).Insert(doc, gorethink.InsertOpts{Conflict: "replace"}).RunWrite(r.client)
	}
	if err != nil {
		r.pipe.Err <- NewError(ERROR, r.path, "rethinkdb error (%s)", err)
		return msg, nil
	}

	err = r.handleResponse(&resp)
	if err != nil {
		r.pipe.Err <- NewError(ERROR, r.path, "rethinkdb error (%s)", err)
	}

	return msg, nil
}
示例#12
0
func getCard(rw http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)

	card_id := vars["card_id"]

	var newCard Card

	res, _ := rt.Table("card").Get(card_id).Run(Session)

	res.One(&newCard)
	data, _ := json.Marshal(newCard)
	rw.Write([]byte(data))
}
示例#13
0
文件: post.go 项目: esiqveland/den
// Get fetches a posting. Make sure to check for err.
// returns ErrPostNotFound for empty result.
func (self *RethinkPosting) Get(id string) (Posting, error) {
	post := Posting{}
	res, err := r.Table(postingsTable).Get(id).Run(self.session)
	if err != nil {
		return post, err
	}
	if res.IsNil() {
		return post, ErrPostNotFound
	}
	err = res.One(&post)
	if err != nil {
		return post, err
	}
	return post, nil
}
示例#14
0
func (r *Rethinkdb) startupChangesForTable(table string, start <-chan bool, wg *sync.WaitGroup) error {
	wg.Add(1)
	defer wg.Done()
	if r.debug {
		fmt.Printf("getting a changes cursor for %s\n", table)
	}
	ccursor, err := gorethink.Table(table).Changes().Run(r.client)
	if err != nil {
		r.pipe.Err <- err
		return err
	}
	// wait until time to start sending changes
	<-start
	if err := r.sendChanges(table, ccursor); err != nil {
		r.pipe.Err <- err
		return err
	}
	return nil
}
示例#15
0
文件: init.go 项目: exu/go-workshops
func main() {
	fmt.Println("Connecting to RethinkDB")

	session, err := r.Connect(r.ConnectOpts{
		Address:  "localhost:7704",
		Database: "players",
	})

	session.SetMaxOpenConns(10)

	if err != nil {
		log.Fatal("Could not connect")
	}

	r.DBDrop("players").Exec(session)
	err = r.DBCreate("players").Exec(session)
	if err != nil {
		panic(err)
	}

	err = r.DB("players").TableDrop("scores").Exec(session)
	err = r.DB("players").TableCreate("scores").Exec(session)
	if err != nil {
		log.Fatal("Could not create table", err)
	}

	err = r.DB("players").Table("scores").IndexCreate("Score").Exec(session)
	if err != nil {
		log.Fatal("Could not create index")
	}

	fmt.Println("Inserting new records")
	for i := 0; i < 10000; i++ {
		player := new(ScoreEntry)
		player.ID = strconv.Itoa(i)
		player.PlayerName = fmt.Sprintf("Player %d", i)
		player.Score = rand.Intn(100)
		_, err := r.Table("scores").Insert(player).RunWrite(session)
		if err != nil {
			log.Fatal(err)
		}
	}
}
示例#16
0
// getAccessData is a common function to get AccessData by field
func (s *RethinkDBStorage) getAccessData(fieldName, token string) (*osin.AccessData, error) {
	result, err := r.Table(accessTable).Filter(r.Row.Field(fieldName).Eq(token)).Run(s.session)
	if err != nil {
		return nil, err
	}
	defer result.Close()

	var dataMap map[string]interface{}
	err = result.One(&dataMap)
	if err != nil {
		return nil, err
	}

	var client osin.Client
	clientID := dataMap["Client"].(map[string]interface{})["Id"].(string)
	client, err = s.GetClient(clientID)
	if err != nil {
		return nil, err
	}
	dataMap["Client"] = client

	if authorizeData := dataMap["AuthorizeData"]; authorizeData != nil {
		if authorizeDataClient := authorizeData.(map[string]interface{})["Client"]; authorizeDataClient != nil {
			var authorizeDataClientStruct osin.Client
			if authorizeDataClientID := authorizeDataClient.(map[string]interface{})["Id"]; authorizeDataClientID != nil {
				authorizeDataClientStruct, err = s.GetClient(authorizeDataClientID.(string))
				if err != nil {
					return nil, err
				}
				dataMap["AuthorizeData"].(map[string]interface{})["Client"] = authorizeDataClientStruct
			}
		}
	}

	var dataStruct osin.AccessData
	err = mapstructure.Decode(dataMap, &dataStruct)
	if err != nil {
		return nil, err
	}

	return &dataStruct, nil
}
示例#17
0
// GetClient returns client with given ID
func (s *RethinkDBStorage) GetClient(clientID string) (osin.Client, error) {
	result, err := r.Table(clientsTable).Filter(r.Row.Field("Id").Eq(clientID)).Run(s.session)
	if err != nil {
		return nil, err
	}
	defer result.Close()

	var clientMap map[string]interface{}
	err = result.One(&clientMap)
	if err != nil {
		return nil, err
	}

	var clientStruct osin.DefaultClient
	err = mapstructure.Decode(clientMap, &clientStruct)
	if err != nil {
		return nil, err
	}

	return &clientStruct, nil
}
示例#18
0
func main() {
	fmt.Println("I'm watching You!")

	session, err := r.Connect(r.ConnectOpts{
		Address:  "localhost:7704",
		Database: "players",
	})

	if err != nil {
		log.Fatal(err)
	}

	res, err := r.Table("scores").Changes().Run(session)

	if err != nil {
		log.Fatalln(err)
	}

	var value interface{}
	for res.Next(&value) {
		fmt.Println(value)
	}
}
示例#19
0
// SaveAuthorize creates a new authorization
func (s *RethinkDBStorage) SaveAuthorize(data *osin.AuthorizeData) error {
	_, err := r.Table(authorizeTable).Insert(data).RunWrite(s.session)
	return err
}
示例#20
0
// CreateClient inserts a new client
func (s *RethinkDBStorage) CreateClient(c osin.Client) error {
	_, err := r.Table(clientsTable).Insert(c).RunWrite(s.session)
	return err
}
示例#21
0
// SaveAccess creates a new access data
func (s *RethinkDBStorage) SaveAccess(data *osin.AccessData) error {
	_, err := r.Table(accessTable).Insert(data).RunWrite(s.session)
	return err
}