Example #1
0
func (s MySuite) SetUpSuite(c *gocheck.C) {
	d, err := Connect("")
	if err != nil {
		c.Fatalf("Unable to connect to database!")
	}
	db = d
	// create a test user
	u := User{ID: bson.NewObjectId(), Email: "*****@*****.**", Phone: "5555555555"}
	err = db.Users.Insert(u)
	if err != nil {
		c.Fatalf("Can't insert document: %v\n", err)
	}
	// create a test notification
	n := Notification{ID: bson.NewObjectId(),
		Type:     "text",
		Team:     "7332",
		User:     "******",
		Advance:  true,
		Award:    true,
		Alliance: true,
	}
	err = db.Notifications.Insert(n)
	if err != nil {
		c.Fatalf("Can't insert document: %v\n", err)
	}
}
Example #2
0
func (this *Article) Save() error {
	this.Id = bson.NewObjectId()
	if len(this.Parent) == 0 {
		if err := save(articleColl, this, true); err != nil {
			return errors.NewError(errors.DbError, err.Error())
		}
		return nil
	}

	if !bson.IsObjectIdHex(this.Parent) {
		return errors.NewError(errors.InvalidMsgError)
	}

	update := bson.M{
		"$push": bson.M{
			"reviews": this.Id.Hex(),
		},
		"$inc": bson.M{
			"review_count": 1,
		},
	}
	if this.Type == ArticleCoach {
		update = bson.M{
			"$addToSet": bson.M{
				"coaches": this.Author,
			},
			"$inc": bson.M{
				"coach_review_count": 1,
			},
		}
	}

	f := func(c *mgo.Collection) error {
		runner := txn.NewRunner(c)
		ops := []txn.Op{
			{
				C:      articleColl,
				Id:     this.Id,
				Assert: txn.DocMissing,
				Insert: this,
			},
			{
				C:      articleColl,
				Id:     bson.ObjectIdHex(this.Parent),
				Assert: txn.DocExists,
				Update: update,
			},
		}

		return runner.Run(ops, bson.NewObjectId(), nil)
	}

	if err := withCollection("comment_tx", &mgo.Safe{}, f); err != nil {
		log.Println(err)
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}
Example #3
0
func main() {
	var (
		mongoSession *mgo.Session
		database     *mgo.Database
		collection   *mgo.Collection
		err          error
	)

	if mongoSession, err = mgo.Dial("localhost"); err != nil {
		panic(err)
	}

	database = mongoSession.DB("mgo_examples_05")
	collection = database.C("todos")

	var todos []Todo
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "First task for today", Created: time.Now(), Due: time.Now().Add(time.Hour * 24)})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Second task for today", Created: time.Now(), Due: time.Now()})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Third task for today", Created: time.Now(), Due: time.Now()})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Fourth task for today", Created: time.Now(), Due: time.Now()})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Fifth task for today", Created: time.Now(), Due: time.Now()})

	for _, todo := range todos {
		if _, err = collection.UpsertId(todo.Id, &todo); err != nil {
			panic(err)
		}
	}
	// START OMIT
	pipeline := []bson.M{
		{"$group": bson.M{
			"_id":   bson.M{"$dayOfYear": "$d"},
			"count": bson.M{"$sum": 1},
		}},
	}

	var (
		result  TodoDueCounts
		results []TodoDueCounts
	)

	iter := collection.Pipe(pipeline).Iter()
	for {
		if iter.Next(&result) {
			results = append(results, result)
		} else {
			break
		}
	}
	err = iter.Err()
	if err != nil {
		panic(err)
	}
	// END OMIT
	fmt.Printf("%# v", pretty.Formatter(results))
}
Example #4
0
func get_decks() []Deck {
	c := make(chan []int32)
	go Get_winner_list(c)
	go Get_winner_list(c)
	go Get_loser_list(c)
	go Get_loser_list(c)
	w, x, y, z := <-c, <-c, <-c, <-c
	d1 := Deck{bson.NewObjectId(), w}
	d2 := Deck{bson.NewObjectId(), x}
	d3 := Deck{bson.NewObjectId(), y}
	d4 := Deck{bson.NewObjectId(), z}
	return []Deck{d1, d2, d3, d4}
}
Example #5
0
func NewPoint(title, location, location_index string,
	userid bson.ObjectId) *Point {
	point := &Point{
		ID:             bson.NewObjectId(),
		Title:          title,
		Location:       location,
		Location_index: location_index,
		UserId:         userid,
		Date:           time.Now(),
		Img:            "/apps/eating/imgs/" + bson.NewObjectId().Hex(),
	}
	return point
}
Example #6
0
func main() {
	logout := log.New(os.Stdout, "MGO: ", log.Lshortfile)
	mgo.SetLogger(logout)
	mgo.SetDebug(false)
	session, err := mgo.Dial("localhost")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	db := session.DB("bookdb")
	cbooks := db.C("bookcoll")
	cauthors := db.C("authorcoll")

	aids := []bson.ObjectId{bson.NewObjectId(), bson.NewObjectId()}
	authors := []Author{{
		aids[0],
		"Author 1",
	}, {
		aids[1],
		"Author 2",
	}}
	cauthors.Insert(authors[0])
	cauthors.Insert(authors[1])
	// Insert some books
	mine := Book{
		bson.NewObjectId(),
		"Gang of four thingy",
		aids,
	}
	cbooks.Insert(&mine)

	var assembl []AssembledBooks
	cauthors.Find(bson.M{}).All(&assembl)
	str1, _ := json.MarshalIndent(assembl, "", " ")
	fmt.Printf("%s\n", str1)

	var allauthors []Author
	cauthors.Find(bson.M{}).All(&allauthors)
	str, _ := json.MarshalIndent(allauthors, "", " ")
	fmt.Printf("%s\n", str)
	var allbooks []Book
	cbooks.Find(bson.M{}).All(&allbooks)
	str, _ = json.MarshalIndent(allbooks, "", " ")
	fmt.Printf("%s\n", str)

	fmt.Println("Dropping all collections...")
	cauthors.DropCollection()
	cbooks.DropCollection()
	fmt.Println("Done")
}
Example #7
0
// 复制别人的共享笔记给我
// TODO 判断是否共享了给我
func (this *NoteService) CopySharedNote(noteId, notebookId, fromUserId, myUserId string) info.Note {
	if notebookService.IsMyNotebook(notebookId, myUserId) {
		note := this.GetNote(noteId, fromUserId)
		if note.NoteId == "" {
			return info.Note{}
		}
		noteContent := this.GetNoteContent(noteId, fromUserId)

		// 重新生成noteId
		note.NoteId = bson.NewObjectId()
		note.NotebookId = bson.ObjectIdHex(notebookId)
		note.UserId = bson.ObjectIdHex(myUserId)
		note.IsTop = false
		note.IsBlog = false // 别人的可能是blog

		// content
		noteContent.NoteId = note.NoteId
		noteContent.UserId = note.UserId

		// 添加之
		note = this.AddNoteAndContent(note, noteContent, note.UserId)

		// 更新blog状态
		isBlog := this.updateToNotebookBlog(note.NoteId.Hex(), notebookId, myUserId)

		note.IsBlog = isBlog
		return note
	}

	return info.Note{}
}
Example #8
0
func (m *MongoService) Save(collection string, docId string, doc models.MongoModel) (info *mgo.ChangeInfo, err error) {
	if docId == "" {
		docId = bson.NewObjectId().Hex()
		doc.SetId(docId)
	}
	return m.getCollection(collection).UpsertId(docId, doc)
}
Example #9
0
// URL: /article/new
// 新建文章
func newArticleHandler(w http.ResponseWriter, r *http.Request) {
	var categories []ArticleCategory
	c := DB.C("articlecategories")
	c.Find(nil).All(&categories)

	var choices []wtforms.Choice

	for _, category := range categories {
		choices = append(choices, wtforms.Choice{Value: category.Id_.Hex(), Label: category.Name})
	}

	form := wtforms.NewForm(
		wtforms.NewHiddenField("html", ""),
		wtforms.NewTextField("title", "标题", "", wtforms.Required{}),
		wtforms.NewTextField("original_source", "原始出处", "", wtforms.Required{}),
		wtforms.NewTextField("original_url", "原始链接", "", wtforms.URL{}),
		wtforms.NewSelectField("category", "分类", choices, ""),
	)

	if r.Method == "POST" && form.Validate(r) {
		user, _ := currentUser(r)

		c = DB.C("contents")

		id_ := bson.NewObjectId()

		html := form.Value("html")
		html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1)

		categoryId := bson.ObjectIdHex(form.Value("category"))
		err := c.Insert(&Article{
			Content: Content{
				Id_:       id_,
				Type:      TypeArticle,
				Title:     form.Value("title"),
				CreatedBy: user.Id_,
				CreatedAt: time.Now(),
			},
			Id_:            id_,
			CategoryId:     categoryId,
			OriginalSource: form.Value("original_source"),
			OriginalUrl:    form.Value("original_url"),
		})

		if err != nil {
			fmt.Println("newArticleHandler:", err.Error())
			return
		}

		http.Redirect(w, r, "/a/"+id_.Hex(), http.StatusFound)
		return
	}

	renderTemplate(w, r, "article/form.html", map[string]interface{}{
		"form":   form,
		"title":  "新建",
		"action": "/article/new",
		"active": "article",
	})
}
Example #10
0
func NewContext(req *http.Request) (*Context, error) {
	sess, err := store.Get(req, COOKIE_NAME)
	ctx := &Context{
		Database: db_session.Clone().DB(database),
		Session:  sess,
		Data:     make(map[string]interface{}),
	}
	if err != nil { // if the above is still an error
		return ctx, err
	}

	//try to fill in the user from the session
	if uid, ok := sess.Values["user"].(bson.ObjectId); ok {
		e := ctx.C("users").Find(bson.M{"_id": uid}).One(&ctx.User)
		if ctx.User != nil {
			ctx.User.Password = []byte{}
			ctx.User.BirthDate = ctx.User.BirthDate.UTC()
		}
		if e != nil {
			Log("error finding user for cookie uid: ", err.Error())
		}
	}
	if _, ok := sess.Values["csrf_token"].(string); !ok {
		ctx.Session.Values["csrf_token"] = bson.NewObjectId().Hex()
	}
	return ctx, err
}
Example #11
0
// newUser create an *auth.User without save it to database.
// Its set an BSON ObjectID and check email,password.
func (m *MgoUserManager) newUser(email, pwd string, app bool) (*auth.User, error) {
	if !m.Formater.EmailValidate(email) {
		return nil, auth.ErrInvalidEmail
	}

	if !m.Formater.PasswordValidate(pwd) {
		return nil, auth.ErrInvalidPassword
	}

	u := &auth.User{}
	u.Id = bson.NewObjectId()
	u.Email = email
	u.LastActivity = time.Now()
	u.Info.JoinDay = u.LastActivity

	p, err := auth.HashPwd(pwd)
	if err != nil {
		return nil, err
	}

	u.Pwd = p

	u.Approved = app
	if !app {
		u.ConfirmCodes = map[string]string{
			"activate": base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(64)),
		}
	}

	return u, nil
}
Example #12
0
// URL: /admin/article_category/new
// 新建文章分类
func adminNewArticleCategoryHandler(handler Handler) {
	form := wtforms.NewForm(
		wtforms.NewTextField("name", "名称", "", wtforms.Required{}),
	)

	if handler.Request.Method == "POST" {
		if !form.Validate(handler.Request) {
			renderTemplate(handler, "article_category/new.html", ADMIN, map[string]interface{}{"form": form})
			return
		}

		c := handler.DB.C(ARTICLE_CATEGORIES)
		var category ArticleCategory
		err := c.Find(bson.M{"name": form.Value("name")}).One(&category)

		if err == nil {
			form.AddError("name", "该名称已经有了")
			renderTemplate(handler, "article_category/new.html", ADMIN, map[string]interface{}{"form": form})
			return
		}

		err = c.Insert(&ArticleCategory{
			Id_:  bson.NewObjectId(),
			Name: form.Value("name"),
		})

		if err != nil {
			panic(err)
		}

		http.Redirect(handler.ResponseWriter, handler.Request, "/admin/article_category/new", http.StatusFound)
	}

	renderTemplate(handler, "article_category/new.html", ADMIN, map[string]interface{}{"form": form})
}
Example #13
0
// URL: /a/{articleId}/comment
// 评论文章
func commentAnArticleHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		vars := mux.Vars(r)
		articleId := vars["articleId"]

		user, ok := currentUser(r)

		if !ok {
			http.Redirect(w, r, "/a/"+articleId, http.StatusFound)
			return
		}

		content := r.FormValue("content")

		html := r.FormValue("html")
		html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1)

		Id_ := bson.NewObjectId()
		now := time.Now()
		comment := Comment{
			Id_:       Id_,
			UserId:    user.Id_,
			Markdown:  content,
			Html:      template.HTML(html),
			CreatedAt: now,
		}

		c := db.C("articles")
		c.Update(bson.M{"_id": bson.ObjectIdHex(articleId)}, bson.M{"$addToSet": bson.M{"comments": comment}})

		http.Redirect(w, r, "/a/"+articleId, http.StatusFound)
	}
}
Example #14
0
func (u *UserMetaData) SaveUserMetaData() RD.ReturnData {
	returnData := RD.ReturnData{}
	dbSession := Connection.GetDBSession()
	dbSession.SetMode(mgo.Monotonic, true)
	dataBase := strings.SplitAfter(os.Getenv("MONGOHQ_URL"), "/")
	c := dbSession.DB(dataBase[3]).C("jove")

	u.Id = bson.NewObjectId()
	u.Created_on = time.Now()

	err := c.Insert(u)
	if err != nil {
		log.Print(err.Error())
		returnData.ErrorMsg = err.Error()
		returnData.Success = false
		returnData.Status = "422"
	} else {
		returnData.Success = true
		jsonData, _ := json.Marshal(&u)
		returnData.JsonData = jsonData
		returnData.Status = "201"
	}

	return returnData
}
Example #15
0
// NameToID - Converts name to ObjectId if its one.
// If `create` is true and name is empty it creates new id and `created` is true.
func NameToID(name interface{}, create bool) (id interface{}, created bool) {
	// If create is true and name is empty - create new id
	if create {
		// If name is nil or empty string
		if n, ok := name.(string); name == nil || ok && n == "" {
			id = bson.NewObjectId()
			created = true
			return
		}
	}

	// Try to cast name to ObjectId
	var ok bool
	if id, ok = name.(bson.ObjectId); ok {
		return
	}

	// By default id is a name
	id = name

	// If name is ObjectIdHex convert it
	if n, ok := name.(string); ok && bson.IsObjectIdHex(n) {
		id = bson.ObjectIdHex(n)
	}

	return
}
Example #16
0
func (this *Tx) Save() error {
	this.Id = bson.NewObjectId()
	if err := save(txColl, this, true); err != nil {
		return errors.NewError(errors.DbError)
	}
	return nil
}
Example #17
0
// Appends an item (map or struct) into the collection.
func (self *Collection) Append(item interface{}) (interface{}, error) {
	var err error
	var id bson.ObjectId

	id = bson.NewObjectId()

	// Allocating a new ID.
	if err = self.collection.Insert(bson.M{"_id": id}); err != nil {
		return nil, err
	}

	// Now append data the user wants to append.
	if err = self.collection.Update(bson.M{"_id": id}, item); err != nil {
		return nil, err
	}

	return id, nil

	/*
		var id bson.ObjectId
		var err error

		id = bson.NewObjectId()

		_, err = self.collection.Upsert(bson.M{"_id": id}, item);

		if err != nil {
			return nil, err
		}

		return id, nil
	*/
}
Example #18
0
// Parse a row returned from SQLite into a Factoid.
func parseFactoid(row []interface{}, out chan *factoids.Factoid) {
	values := parseMultipleValues(toString(row[cValue]))
	c := &factoids.FactoidStat{
		Nick:  base.Nick(toString(row[cCreator])),
		Chan:  "",
		Count: 1,
	}
	c.Timestamp, _ = parseTimestamp(row[cCreated])
	m := &factoids.FactoidStat{Chan: "", Count: 0}
	if ts, ok := parseTimestamp(row[cModified]); ok {
		m.Timestamp = ts
		m.Nick = base.Nick(toString(row[cModifier]))
		m.Count = 1
	} else {
		m.Timestamp = c.Timestamp
		m.Nick = c.Nick
	}
	p := &factoids.FactoidPerms{
		parseReadOnly(row[cAccess]),
		base.Nick(toString(row[cCreator])),
	}
	for _, val := range values {
		t, v := parseValue(toString(row[cKey]), toString(row[cRel]), val)
		if v == "" {
			// skip the many factoids with empty values.
			continue
		}
		out <- &factoids.Factoid{
			Key: toString(row[cKey]), Value: v, Type: t, Chance: 1.0,
			Created: c, Modified: m, Accessed: c, Perms: p,
			Id: bson.NewObjectId(),
		}
	}
}
Example #19
0
// Add - Adds action from database.
func (a *StoreAction) Add() (err error) {
	// Get database session
	sess := Session.Copy()
	defer sess.Close()

	// Get database connection
	actions := sess.DB("").C(ActionsCollection)

	// Create query selector without action
	var q *StoreAction
	if a.Action != nil {
		q = &StoreAction{
			Project: a.Project,
			User:    a.User,
			Name:    a.Name,
		}
	} else {
		q = a
	}

	// Find action if any
	if err := actions.Find(q).One(q); err == nil {
		a.ID = q.ID
	} else {
		a.ID = bson.NewObjectId()
	}

	// Upsert action - insert or replace
	_, err = actions.UpsertId(a.ID, a)
	return
}
func NewLoginSession(user *User) *LoginSession {
	return &LoginSession{
		Cookie:     bson.NewObjectId(),
		User:       user,
		Expiretime: time.Now().AddDate(0, 0, 7),
	}
}
Example #21
0
func Test_getSession(t *testing.T) {
	c, session, err := connect(sessions)
	if err != nil {
		t.Fatal(err)
	}
	defer session.Close()

	t.Logf("Test SessionId does not exist.")
	sessionId := &SessionId{Id: bson.NewObjectId(), Username: "******"}
	if result, err := getSession(session, sessionId); err != mgo.ErrNotFound {
		t.Error(err)
	} else if result != nil {
		t.Error("result is not nil")
	}

	t.Logf("Test SessionId exists.")
	sessionId, err = startSession(session, "Nemo")
	if err != nil {
		t.Fatal(err)
	}
	if result, err := getSession(session, sessionId); err != nil {
		t.Error(err)
	} else if result == nil {
		t.Error("result is nil")
	}

	if err = c.Remove(sessionId); err != nil {
		t.Error(err)
	}
}
Example #22
0
func SendMessage(w http.ResponseWriter, req *http.Request, ctx *models.Context) error {
	if ctx.User == nil {
		http.Redirect(w, req, reverse("login"), http.StatusSeeOther)
		return nil
	}
	to := req.URL.Query().Get(":to")
	if !bson.IsObjectIdHex(to) {
		return perform_status(w, req, http.StatusForbidden)
	}
	if to == ctx.User.Id.Hex() {
		return perform_status(w, req, http.StatusForbidden)
	}
	m := models.Message{
		Id:       bson.NewObjectId(),
		From:     ctx.User.Id,
		To:       bson.ObjectIdHex(to),
		UserName: ctx.User.FullName(),
		Avatar:   ctx.User.Avatar,
		Subject:  req.FormValue("subject"),
		Body:     req.FormValue("body"),
	}
	if err := ctx.C(M).Insert(m); err != nil {
		models.Log("Error sending message: ", err.Error())
	}
	return nil
}
Example #23
0
func NewQueueItem(registry *registry.Registry, command string,
	source *document.DocumentID, target *document.DocumentID,
	sourceRange string, targetRange string,
	payload io.Reader) (*QueueItem, error) {
	buf := new(bytes.Buffer)
	w, _ := gzip.NewWriterLevel(buf, gzip.BestSpeed)
	if _, err := io.Copy(w, payload); err != nil {
		return nil, newQueueError("Queue Item gzip copy:", err)
	}
	if err := w.Close(); err != nil {
		return nil, newQueueError("Queue Item gzip close:", err)
	}
	item := &QueueItem{
		Id:          bson.NewObjectId(),
		Command:     command,
		Status:      "Queued",
		Source:      source,
		Target:      target,
		SourceRange: sourceRange,
		TargetRange: targetRange,
		Payload:     buf.Bytes(),
	}
	if err := item.Save(registry); err != nil {
		return nil, newQueueError("Queue Item save:", err)
	}
	return item, nil
}
Example #24
0
func (s *AEServer) HandlePostQuestion(w http.ResponseWriter, r *http.Request, session sessions.Session) (int, string) {
	//Verify user account or something
	login := session.Get("Login")
	if login == nil {
		return 404, Message("Not Logged In!")
	}
	tok := login.(string)
	user := s.syncGetUser(tok)
	if user == nil {
		return http.StatusBadRequest, Message("Invalid Cookie!")
	}

	q := QuestionFromJson(r.Body)
	if q == nil {
		return 404, Message("Poorly Formatted JSON.")
	}
	//Assign question an ID
	q.ID = bson.NewObjectId()
	q.Author = user.Username
	q.Timestamp = time.Now()

	err := s.questions.Save(q)
	if err != nil {
		log.Print(err)
		return http.StatusInternalServerError, Message("Failed to save question")
	}
	return 200, q.GetIdHex()
}
Example #25
0
func (s *S) TestNewObjectId(c *C) {
	// Generate 10 ids
	ids := make([]bson.ObjectId, 10)
	for i := 0; i < 10; i++ {
		ids[i] = bson.NewObjectId()
	}
	for i := 1; i < 10; i++ {
		prevId := ids[i-1]
		id := ids[i]
		// Test for uniqueness among all other 9 generated ids
		for j, tid := range ids {
			if j != i {
				c.Assert(id, Not(Equals), tid, Commentf("Generated ObjectId is not unique"))
			}
		}
		// Check that timestamp was incremented and is within 30 seconds of the previous one
		secs := id.Time().Sub(prevId.Time()).Seconds()
		c.Assert((secs >= 0 && secs <= 30), Equals, true, Commentf("Wrong timestamp in generated ObjectId"))
		// Check that machine ids are the same
		c.Assert(id.Machine(), DeepEquals, prevId.Machine())
		// Check that pids are the same
		c.Assert(id.Pid(), Equals, prevId.Pid())
		// Test for proper increment
		delta := int(id.Counter() - prevId.Counter())
		c.Assert(delta, Equals, 1, Commentf("Wrong increment in generated ObjectId"))
	}
}
Example #26
0
func CreateTicket(ctx *auth.AuthContext, rw http.ResponseWriter, req *http.Request) (int, error) {
	// developer can call:
	// user, err := ctx.ValidCurrentUser(false, nil)
	// to get the current logged user's infomation
	t := Ticket{}
	err := json.NewDecoder(req.Body).Decode(&t)
	req.Body.Close()
	if err != nil {
		return http.StatusBadRequest, err
	}

	t.Id = bson.NewObjectId()

	// save stuff to database
	db, ok := ctx.Value(DBKey).(*mgo.Database)
	if !ok {
		ctx.Logs.Errorf("Cannot access database")
		return http.StatusInternalServerError, errors.New("Cannot access database")
	}

	err = db.C("tickets").Insert(&t)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	json.NewEncoder(rw).Encode(&t)
	return http.StatusOK, nil
}
Example #27
0
File: revmgo.go Project: x6j/revmgo
func AppInit() {
	var err error
	// Read configuration.
	Dial = revel.Config.StringDefault("revmgo.dial", "localhost")
	Method = revel.Config.StringDefault("revmgo.method", "clone")
	if err = MethodError(Method); err != nil {
		revel.ERROR.Panic(err)
	}

	// Let's try to connect to Mongo DB right upon starting revel but don't
	// raise an error. Errors will be handled if there is actually a request
	if Session == nil {
		Session, err = mgo.Dial(Dial)
		if err != nil {
			// Only warn since we'll retry later for each request
			revel.WARN.Printf("Could not connect to Mongo DB. Error: %s", err)
		} else {
			setDuplMethod()
		}
	}

	// register the custom bson.ObjectId binder
	objId := bson.NewObjectId()
	revel.TypeBinders[reflect.TypeOf(objId)] = ObjectIdBinder
}
Example #28
0
// 创建机器人
func (r *room) createRebot() error {
	rebotId := newRebotId()

	// 创建一个虚拟的在线用户
	u := &onlineUser{
		model.Users{
			Id_:         bson.NewObjectId(),
			UserId:      rebotId,
			UserName:    fmt.Sprintf("机器人%d", rebotId),
			UserPwd:     "",
			UserCoin:    0,
			UserWin:     0,
			UserLose:    0,
			UserRegTime: time.Now(),
		},
		r.Id,
	}

	h.addOnlineUser(u)

	if err := r.addPlayer(rebotId, true); err != nil {
		fmt.Println("添加机器人进入房间失败:", rebotId, err)
		return err
	}

	r.Rebot = true

	return nil
}
Example #29
0
// Create creates a new file with the provided name in the GridFS.  If the file
// name already exists, a new version will be inserted with an up-to-date
// uploadDate that will cause it to be atomically visible to the Open and
// OpenId methods.  If the file name is not important, an empty name may be
// provided and the file Id used instead.
//
// It's important to Close files whether they are being written to
// or read from, and to check the err result to ensure the operation
// completed successfully.
//
// A simple example inserting a new file:
//
//     func check(err os.Error) {
//         if err != nil {
//             panic(err.String())
//         }
//     }
//     file, err := db.GridFS("fs").Create("myfile.txt")
//     check(err)
//     n, err := file.Write([]byte("Hello world!")
//     check(err)
//     err = file.Close()
//     check(err)
//     fmt.Printf("%d bytes written\n", n)
//
// The io.Writer interface is implemented by *GridFile and may be used to
// help on the file creation.  For example:
//
//     file, err := db.GridFS("fs").Create("myfile.txt")
//     check(err)
//     messages, err := os.Open("/var/log/messages")
//     check(err)
//     defer messages.Close()
//     err = io.Copy(file, messages)
//     check(err)
//     err = file.Close()
//     check(err)
//
func (gfs *GridFS) Create(name string) (file *GridFile, err error) {
	file = gfs.newFile()
	file.mode = gfsWriting
	file.wsum = md5.New()
	file.doc = gfsFile{Id: bson.NewObjectId(), ChunkSize: 256 * 1024, Filename: name}
	return
}
Example #30
0
// NewPoll returns a new poll with
func NewPoll(question string, choices ...*Choice) *Poll {
	return &Poll{
		Id:       bson.NewObjectId(),
		Question: question,
		Choices:  choices,
	}
}