本文整理汇总了Golang中labix/org/v2/mgo.Session类的典型用法代码示例。如果您正苦于以下问题:Golang Session类的具体用法?Golang Session怎么用?Golang Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getKeys
// Get the list of all SSH keys allowed to access a box.
func getKeys(session *mgo.Session, boxname string) (boxUsers, usernames []string, keys string) {
this_session := session.Clone()
defer this_session.Close()
db := this_session.DB("")
staff := getStaff(db)
boxUsers = usersFromBox(db, boxname)
usernames = combineUsers(staff, boxUsers) // returned
// Looks through `canBeReally`.
keySlice := allKeysFromUsernames(db, usernames)
for _, k := range keySlice {
k = strings.Replace(k, "\n", "", -1)
if !strings.HasPrefix(k, "ssh-") && !strings.HasPrefix(k, "#") {
keys += "# NOT VAILD: "
}
keys += k + "\n"
}
return
}
示例2: CloseSession
// CloseSession puts the connection back into the pool
func CloseSession(sessionId string, mongoSession *mgo.Session) {
defer helper.CatchPanic(nil, sessionId, "CloseSession")
tracelog.Started(sessionId, "CloseSession")
mongoSession.Close()
tracelog.Completed(sessionId, "CloseSession")
}
示例3: New
// New returns a new mongo store
func New(session mgo.Session, database string, collection string, maxAge int, ensureTTL bool, keyPairs ...[]byte) nSessions.Store {
if ensureTTL {
conn := session.Clone()
defer conn.Close()
db := conn.DB(database)
c := db.C(collection)
c.EnsureIndex(mgo.Index{
Key: []string{"modified"},
Background: true,
Sparse: true,
ExpireAfter: time.Duration(maxAge) * time.Second,
})
}
return &mongoStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Token: nSessions.NewCookieToken(),
session: session,
database: database,
collection: collection,
options: &gSessions.Options{
MaxAge: maxAge,
},
}
}
示例4: Handler
// Handler returns a http.Handler
func Handler(path string, dbsess *mgo.Session, tmpl *view.View) *handler {
h := &handler{}
h.dbsess = dbsess
h.tmpl = tmpl
h.path = path
h.initSubRoutes()
h.notifer = membership.NewSMTPNotificater(
CONFIG.Get("smtp_email").(string),
CONFIG.Get("smtp_pass").(string),
CONFIG.Get("smtp_addr").(string),
int(CONFIG.Get("smtp_port").(float64)),
)
dbsess.DB(DBNAME).C("toysSession").EnsureIndex(mgo.Index{
Key: []string{"lastactivity"},
ExpireAfter: 7200 * time.Second,
})
dbsess.DB(DBNAME).C("toysUser").EnsureIndex(mgo.Index{
Key: []string{"email"},
Unique: true,
})
return h
}
示例5: Insert
// Save the DataModel to DataStore
func Insert(mgo_db string, m DataModel, conn *mgo.Session) (err error) {
if conn == nil {
conn, err = MgoConnGet(mgo_db)
if err != nil {
return
}
defer conn.Close()
}
if conn != nil {
c := conn.DB(mgo_db).C(m.Type())
if len(m.MidGet()) == 0 {
m.MidSet(bson.NewObjectId())
}
if err = c.Insert(m); err != nil {
Log(ERROR, "MGOU ERROR on insert ", err, " TYPE=", m.Type(), " ", m.MidGet())
} else {
//Log(DEBUG, "successfully inserted!!!!!! ", m.MidGet(), " oid=", m.OidGet())
}
} else {
Log(ERROR, "MGOU Nil connection")
return errors.New("no db connection")
}
return
}
示例6: SaveModel
// Save the DataModel to DataStore
func SaveModel(mgo_db string, m DataModel, conn *mgo.Session) (err error) {
if conn == nil {
conn, err = MgoConnGet(mgo_db)
if err != nil {
return
}
defer conn.Close()
}
if conn != nil {
bsonMid := m.MidGet()
c := conn.DB(mgo_db).C(m.Type())
//Debug("SAVING ", mgo_db, " type=", m.Type(), " Mid=", bsonMid)
if len(bsonMid) < 5 {
m.MidSet(bson.NewObjectId())
if err = c.Insert(m); err != nil {
Log(ERROR, "MGOU ERROR on insert ", err, " TYPE=", m.Type(), " ", m.MidGet())
} else {
//Log(DEBUG, "successfully inserted!!!!!! ", m.MidGet(), " oid=", m.OidGet())
}
} else {
// YOU MUST NOT SEND Mid "_id" to Mongo
mid := m.MidGet()
m.MidSet("") // omitempty means it doesn't get sent
if err = c.Update(bson.M{"_id": bson.ObjectId(bsonMid)}, m); err != nil {
Log(ERROR, "MGOU ERROR on update ", err, " ", bsonMid, " MID=?", m.MidGet())
}
m.MidSet(mid)
}
} else {
Log(ERROR, "MGOU Nil connection")
return errors.New("no db connection")
}
return
}
示例7: Initiate
// Initiate sets up a replica set with the given replica set name with the
// single given member. It need be called only once for a given mongo replica
// set. The tags specified will be added as tags on the member that is created
// in the replica set.
//
// Note that you must set DialWithInfo and set Direct = true when dialing into a
// specific non-initiated mongo server.
//
// See http://docs.mongodb.org/manual/reference/method/rs.initiate/ for more
// details.
func Initiate(session *mgo.Session, address, name string, tags map[string]string) error {
monotonicSession := session.Clone()
defer monotonicSession.Close()
monotonicSession.SetMode(mgo.Monotonic, true)
cfg := Config{
Name: name,
Version: 1,
Members: []Member{{
Id: 1,
Address: address,
Tags: tags,
}},
}
logger.Infof("Initiating replicaset with config %#v", cfg)
var err error
for i := 0; i < maxInitiateAttempts; i++ {
err = monotonicSession.Run(bson.D{{"replSetInitiate", cfg}}, nil)
if err != nil && err.Error() == rsMembersUnreachableError {
time.Sleep(initiateAttemptDelay)
continue
}
break
}
return err
}
示例8: makeHandler
/*
* makeHandler warps around handlers providing them with a session, and automatically closing that session
* to prevent loosing memory.
*/
func makeHandler(fn func(http.ResponseWriter, *http.Request, *mgo.Session), session *mgo.Session) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s := session.Copy() // Create a copy of the session
fn(w, r, s)
s.Close() // Close the copy
}
}
示例9: main
func main() {
var (
mongoSession *mgo.Session
database *mgo.Database
collection *mgo.Collection
changeInfo *mgo.ChangeInfo
err error
)
if mongoSession, err = mgo.Dial("localhost"); err != nil {
panic(err)
}
database = mongoSession.DB("mgo_examples_03")
collection = database.C("todos")
// START OMIT
var todo = Todo{
Id: bson.NewObjectId(),
Task: "Demo mgo",
Created: time.Now(),
}
// This is a shortcut to collection.Upsert(bson.M{"_id": todo.id}, &todo)
if changeInfo, err = collection.UpsertId(todo.Id, &todo); err != nil {
panic(err)
}
// END OMIT
fmt.Printf("Todo: %# v", pretty.Formatter(todo))
fmt.Printf("Change Info: %# v", pretty.Formatter(changeInfo))
}
示例10: processServerSendUsers
func processServerSendUsers(m map[string]interface{}, session *mgo.Session) {
log.Println("PARSING server_send_users")
// wholesale replace users collection
log.Println("wholesale replace users collection")
c := session.DB("landline").C("Users")
c.RemoveAll(bson.M{})
for k, v := range m["users"].([]interface{}) {
log.Println(k)
object := v.(map[string]interface{})
// create object
object_map := make(map[string]interface{})
object_map["encrypted_kek"] = object["encrypted_kek"].(string)
object_map["encrypted_rsa_private"] = object["encrypted_rsa_private"].(string)
object_map["hashed_password"] = object["hashed_password"].(string)
object_map["rsa_public"] = object["rsa_public"].(string)
object_map["username"] = object["username"].(string)
err := c.Insert(object_map)
if err != nil {
panic(err)
}
}
}
示例11: read_mongodb_static_size
func read_mongodb_static_size(f *IOFilterProtocol, session *mgo.Session) bool {
disk_usage := &f.disk_usage
var stats bson.M
var temp int
admindb := session.DB("admin")
// NOTE: admindb.Login is not necessary if we connect to mongodb
// through 'localhost'
err := admindb.Run(bson.D{{"dbStats", 1}, {"scale", 1}}, &stats)
if err != nil {
logger.Error("Failed to get database %s stats [%s].", "admin", err)
return false
}
if !parse_dbstats(stats["nsSizeMB"], &temp) {
logger.Error("Failed to read admin_namespace_size.")
return false
}
admin_namespace_size := uint64(temp * 1024 * 1024)
disk_usage.static_size += admin_namespace_size
if !parse_dbstats(stats["fileSize"], &temp) {
logger.Error("Failed to read admin_data_file_size.")
return false
}
admin_data_file_size := uint64(temp)
disk_usage.static_size += admin_data_file_size
logger.Debug("Get static disk files size %d.", disk_usage.static_size)
return true
}
示例12: clientDiffRequest
func clientDiffRequest(wsConn *websocket.Conn, session *mgo.Session) {
// init client_diff_request
response_map := make(map[string]interface{})
response_map["action"] = "client_diff_request"
// find syncable object uuids
cb := session.DB("landline").C("SyncableObjects")
var m_result []map[string]interface{}
err := cb.Find(bson.M{}).All(&m_result)
if err != nil {
log.Println(err)
} else {
// objects that the clients knows, but the server may not
object_uuids := make(map[string]interface{})
// loop results
for u, result := range m_result {
_ = u
object_uuids[result["uuid"].(string)] = result["time_modified_since_creation"]
}
response_map["object_uuids"] = object_uuids
// send it over websocket
wsConn.WriteJSON(response_map)
log.Println("Wrote message:")
jsonString, _ := json.Marshal(response_map)
log.Println(string(jsonString))
}
}
示例13: Router
func Router(session *mgo.Session) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
user_agent := new(ua.UserAgent)
user_agent.Parse(req.Header.Get("User-Agent"))
url := req.FormValue("url")
engine_name, engine_version := user_agent.Engine()
browser_name, browser_version := user_agent.Browser()
url_document := &URL{
Date: time.Now(),
Uri: url,
Mobile: user_agent.Mobile(),
Bot: user_agent.Bot(),
Mozilla: user_agent.Mozilla(),
Platform: user_agent.Platform(),
Os: user_agent.OS(),
EngineName: engine_name,
EngineVersion: engine_version,
BrowserName: browser_name,
BrowserVersion: browser_version,
}
c := session.DB("goanywhere").C("urls")
err := c.Insert(url_document)
if err != nil {
panic(err)
}
http.Redirect(w, req, url, http.StatusFound)
}
}
示例14: lastDocument
func lastDocument(session *mgo.Session) {
var m bson.M
coll := session.DB(mongoDb).C(mongoColl)
coll.Find(nil).Sort("-_id").One(&m)
js, _ := json.MarshalIndent(&m, "", " ")
fmt.Println(string(js))
}
示例15: RunQuery
// RunQuery is a function that is launched as a goroutine to perform
// the MongoDB work.
func RunQuery(query int, waitGroup *sync.WaitGroup, mongoSession *mgo.Session) {
// Decrement the wait group count so the program knows this
// has been completed once the goroutine exits.
defer waitGroup.Done()
// Request a socket connection from the session to process our query.
// Close the session when the goroutine exits and put the connection back
// into the pool.
sessionCopy := mongoSession.Copy()
defer sessionCopy.Close()
// Get a collection to execute the query against.
collection := sessionCopy.DB(TestDatabase).C("buoy_stations")
log.Printf("RunQuery : %d : Executing\n", query)
// Retrieve the list of stations.
var buoyStations []BuoyStation
err := collection.Find(nil).All(&buoyStations)
if err != nil {
log.Printf("RunQuery : ERROR : %s\n", err)
return
}
log.Printf("RunQuery : %d : Count[%d]\n", query, len(buoyStations))
}