How to use Get method of mgo Package

Best Keploy code snippet using mgo.Get

server.go

Source:server.go Github

copy

Full Screen

...21 DB_name string22)23func init() {24 var err error25 base_path = os.Getenv("PARKOUR_BASE")26 DB_name = os.Getenv("MONGO_DB_NAME")27 user := os.Getenv("MONGO_USER")28 pass := os.Getenv("MONGO_PASS")29 host := os.Getenv("MONGO_HOST")30 port := os.Getenv("MONGO_PORT")31 mgo_session, err = mgo.Dial("mongodb://" + user + ":" + pass + "@" + host + ":" + port + "/" + DB_name)32 if err != nil {33 panic(err)34 }35}36type Server struct {37 Connections map[*websocket.Conn]string38 Users map[string][]*websocket.Conn39 broadcastCh chan map[string]interface{}40 messageCh chan *Message41 removeCh chan *websocket.Conn42 mutex *sync.Mutex43}44func (s *Server) addConnection(conn *websocket.Conn, id string) {45 s.mutex.Lock()46 defer s.mutex.Unlock()47 s.Connections[conn] = id48 connections, ok := s.Users[id]49 if ok {50 s.Users[id] = append(connections, conn)51 } else {52 s.Users[id] = []*websocket.Conn{conn}53 }54}55func (s *Server) removeConnection(conn *websocket.Conn) {56 s.mutex.Lock()57 defer s.mutex.Unlock()58 delete(s.Connections, conn)59 id := s.Connections[conn]60 connections := s.Users[id]61 for i, c := range connections {62 if c == conn {63 //Delete connection at index i64 connections[i], connections = connections[len(connections)-1], connections[:len(connections)-1]65 }66 }67 s.Users[id] = connections68}69func (s *Server) sendMessage(data map[string]interface{}, conn *websocket.Conn) {70 s.mutex.Lock()71 defer s.mutex.Unlock()72 if err := conn.WriteJSON(data); err != nil {73 s.removeCh <- conn74 }75}76func (s *Server) listen() {77 for {78 select {79 case message := <-s.broadcastCh:80 for connection := range s.Connections {81 s.sendMessage(message, connection)82 }83 case conn := <-s.removeCh:84 s.removeConnection(conn)85 case msg := <-s.messageCh:86 for _, user := range msg.To {87 conns := s.Users[user]88 for _, conn := range conns {89 s.sendMessage(msg.Body, conn)90 }91 }92 }93 }94}95func getBoutData(bout map[string]interface{}) map[string]interface{} {96 mgo_conn := mgo_session.Copy()97 defer mgo_conn.Close()98 mgo_conn.SetMode(mgo.Monotonic, true)99 var users []map[string]interface{}100 var userids []bson.ObjectId101 userslice := bout["users"].([]interface{})102 for _, u := range userslice {103 id := u.(string)104 userids = append(userids, bson.ObjectIdHex(id))105 }106 err := mgo_conn.DB(DB_name).C("users").Find(bson.M{107 "_id": bson.M{108 "$in": userids,109 },110 }).All(&users)111 if err != nil {112 log.Fatalln(err.Error())113 return nil114 }115 bout["users"] = users116 var course map[string]interface{}117 courseid := bout["course"].(string)118 err = mgo_conn.DB(DB_name).C("courses").FindId(bson.ObjectIdHex(courseid)).Select(bson.M{119 "name": 1,120 "code": 1,121 }).One(&course)122 if err != nil {123 log.Fatalln(err.Error())124 return nil125 }126 bout["course"] = course127 return bout128}129func main() {130 secret := "I<3Unicorns"131 r := gin.Default()132 r.Use(CORSMiddleware())133 server := &Server{134 Connections: make(map[*websocket.Conn]string, 0),135 Users: make(map[string][]*websocket.Conn, 0),136 broadcastCh: make(chan map[string]interface{}, 100),137 removeCh: make(chan *websocket.Conn, 100),138 messageCh: make(chan *Message, 100),139 mutex: new(sync.Mutex),140 }141 //Start websocket server.142 go server.listen()143 //Public routes.144 public := r.Group("/api")145 //Private routes. Will need a token to be used with.146 private := r.Group("/api", tokenMiddleWare(secret))147 public.GET("/login/kth", func(c *gin.Context) {148 url := []byte(c.Request.URL.Query().Get("url"))149 c.Redirect(http.StatusTemporaryRedirect, "https://login.kth.se/login?service="+base_path+"/login/callback/kth/"+base64.StdEncoding.EncodeToString(url))150 })151 public.GET("/login/callback/kth/:callback", func(c *gin.Context) {152 mgo_conn := mgo_session.Copy()153 defer mgo_conn.Close()154 mgo_conn.SetMode(mgo.Monotonic, true)155 callback := c.Params.ByName("callback")156 decoded, _ := base64.StdEncoding.DecodeString(callback)157 callbackurl := string(decoded)158 ticket := c.Request.URL.Query().Get("ticket")159 client := new(http.Client)160 res, err := client.Get("https://login.kth.se/serviceValidate?ticket=" + ticket + "&service=" + base_path + "/login/callback/kth/" + callback)161 if err != nil {162 c.Fail(500, err)163 return164 }165 data, err := ioutil.ReadAll(res.Body)166 if err != nil {167 c.Fail(500, err)168 return169 }170 doc, err := mxj.NewMapXml(data, false)171 if err != nil {172 c.Fail(500, err)173 return174 }175 serv := doc["serviceResponse"].(map[string]interface{})176 result := serv["authenticationSuccess"].(map[string]interface{})177 userid := result["user"].(string)178 out, err := exec.Command("ldapsearch", "-x", "-LLL", "ugKthid="+userid).Output()179 if err != nil {180 c.Fail(500, err)181 return182 }183 reg := regexp.MustCompile("(?m)^([^:]+): ([^\n]+)$")184 matches := reg.FindAllStringSubmatch(string(out), -1)185 matchmap := make(map[string]string)186 for _, match := range matches {187 key := match[1]188 value := match[2]189 matchmap[key] = value190 }191 username := matchmap["uid"]192 name := matchmap["cn"]193 firstname := matchmap["givenName"]194 userData := map[string]interface{}{195 "kthid": username,196 "firstname": firstname,197 "name": name,198 }199 id := updateLoginInfo(mgo_conn, userData)200 payload := make(map[string]interface{})201 payload["name"] = userData["name"]202 payload["_id"] = id203 payload["exp"] = time.Now().Add(time.Hour * 24).Unix()204 token, err := generateToken([]byte(secret), &payload)205 if err != nil {206 c.Fail(500, err)207 return208 }209 c.Redirect(http.StatusTemporaryRedirect, callbackurl+"?token="+token)210 })211 private.GET("/ws", func(c *gin.Context) {212 u, _ := c.Get("user")213 user := u.(map[string]interface{})214 conn, err := websocket.Upgrade(c.Writer, c.Request, nil, 1024, 1024)215 if err != nil {216 c.Fail(500, err)217 return218 }219 id := user["_id"].(string)220 server.addConnection(conn, id)221 })222 private.POST("/bouts", func(c *gin.Context) {223 u, _ := c.Get("user")224 user := u.(map[string]interface{})225 bout := new(Bout)226 if c.Bind(bout) {227 mgo_conn := mgo_session.Copy()228 defer mgo_conn.Close()229 mgo_conn.SetMode(mgo.Monotonic, true)230 userid := user["_id"].(string)231 bout.Creator = userid232 bout.Users = append(bout.Users, userid)233 err := mgo_conn.DB(DB_name).C("bouts").Insert(bout)234 if err != nil {235 c.Fail(500, err)236 return237 }238 c.JSON(200, gin.H{"status": "ok"})239 }240 })241 private.GET("/bouts", func(c *gin.Context) {242 mgo_conn := mgo_session.Copy()243 defer mgo_conn.Close()244 mgo_conn.SetMode(mgo.Monotonic, true)245 u, _ := c.Get("user")246 user := u.(map[string]interface{})247 userid := user["_id"].(string)248 var result []map[string]interface{}249 err := mgo_conn.DB("parkour").C("bouts").Find(bson.M{250 "users": bson.M{251 "$in": []string{userid},252 },253 }).Select(bson.M{254 "_id": 1,255 "users": 1,256 "course": 1,257 "lab": 1,258 }).All(&result)259 if err != nil {260 c.Fail(404, err)261 return262 }263 for _, bout := range result {264 bout = getBoutData(bout)265 }266 c.JSON(200, result)267 })268 private.GET("/bouts/:bout", func(c *gin.Context) {269 bout := c.Params.ByName("bout")270 mgo_conn := mgo_session.Copy()271 defer mgo_conn.Close()272 mgo_conn.SetMode(mgo.Monotonic, true)273 boutid := bson.ObjectIdHex(bout)274 var result map[string]interface{}275 err := mgo_conn.DB("parkour").C("bouts").FindId(boutid).One(&result)276 if err != nil {277 c.Fail(500, err)278 return279 }280 result = getBoutData(result)281 c.JSON(200, result)282 })283 /*284 {285 user: "id",286 action: "start"287 }288 */289 private.POST("/bouts/:bout/logs", func(c *gin.Context) {290 bout := c.Params.ByName("bout")291 u, _ := c.Get("user")292 user := u.(map[string]interface{})293 boutlog := new(Log)294 if c.Bind(boutlog) {295 mgo_conn := mgo_session.Copy()296 defer mgo_conn.Close()297 mgo_conn.SetMode(mgo.Monotonic, true)298 boutlog.Date = time.Now()299 id := user["_id"].(string)300 boutlog.ID = bson.NewObjectId()301 boutlog.Creator = id302 //Save boutlog to DB303 boutid := bson.ObjectIdHex(bout)304 err := mgo_conn.DB(DB_name).C("bouts").UpdateId(boutid, bson.M{305 "$push": bson.M{...

Full Screen

Full Screen

Mgo.go

Source:Mgo.go Github

copy

Full Screen

...157 _, err := collection.UpdateAll(query, i)158 return Err(err)159}160func UpdateByIdAndUserId(collection *mgo.Collection, id, userId string, i interface{}) bool {161 err := collection.Update(GetIdAndUserIdQ(id, userId), i)162 return Err(err)163}164func UpdateByIdAndUserId2(collection *mgo.Collection, id, userId bson.ObjectId, i interface{}) bool {165 err := collection.Update(GetIdAndUserIdBsonQ(id, userId), i)166 return Err(err)167}168func UpdateByIdAndUserIdField(collection *mgo.Collection, id, userId, field string, value interface{}) bool {169 return UpdateByIdAndUserId(collection, id, userId, bson.M{"$set": bson.M{field: value}})170}171func UpdateByIdAndUserIdMap(collection *mgo.Collection, id, userId string, v bson.M) bool {172 return UpdateByIdAndUserId(collection, id, userId, bson.M{"$set": v})173}174func UpdateByIdAndUserIdField2(collection *mgo.Collection, id, userId bson.ObjectId, field string, value interface{}) bool {175 return UpdateByIdAndUserId2(collection, id, userId, bson.M{"$set": bson.M{field: value}})176}177func UpdateByIdAndUserIdMap2(collection *mgo.Collection, id, userId bson.ObjectId, v bson.M) bool {178 return UpdateByIdAndUserId2(collection, id, userId, bson.M{"$set": v})179}180//181func UpdateByQField(collection *mgo.Collection, q interface{}, field string, value interface{}) bool {182 _, err := collection.UpdateAll(q, bson.M{"$set": bson.M{field: value}})183 return Err(err)184}185func UpdateByQI(collection *mgo.Collection, q interface{}, v interface{}) bool {186 _, err := collection.UpdateAll(q, bson.M{"$set": v})187 return Err(err)188}189// 查询条件和值190func UpdateByQMap(collection *mgo.Collection, q interface{}, v interface{}) bool {191 _, err := collection.UpdateAll(q, bson.M{"$set": v})192 return Err(err)193}194//------------------------195// 删除一条196func Delete(collection *mgo.Collection, q interface{}) bool {197 err := collection.Remove(q)198 return Err(err)199}200func DeleteByIdAndUserId(collection *mgo.Collection, id, userId string) bool {201 err := collection.Remove(GetIdAndUserIdQ(id, userId))202 return Err(err)203}204func DeleteByIdAndUserId2(collection *mgo.Collection, id, userId bson.ObjectId) bool {205 err := collection.Remove(GetIdAndUserIdBsonQ(id, userId))206 return Err(err)207}208// 删除所有209func DeleteAllByIdAndUserId(collection *mgo.Collection, id, userId string) bool {210 _, err := collection.RemoveAll(GetIdAndUserIdQ(id, userId))211 return Err(err)212}213func DeleteAllByIdAndUserId2(collection *mgo.Collection, id, userId bson.ObjectId) bool {214 _, err := collection.RemoveAll(GetIdAndUserIdBsonQ(id, userId))215 return Err(err)216}217func DeleteAll(collection *mgo.Collection, q interface{}) bool {218 _, err := collection.RemoveAll(q)219 return Err(err)220}221//-------------------------222func Get(collection *mgo.Collection, id string, i interface{}) {223 collection.FindId(bson.ObjectIdHex(id)).One(i)224}225func Get2(collection *mgo.Collection, id bson.ObjectId, i interface{}) {226 collection.FindId(id).One(i)227}228func GetByQ(collection *mgo.Collection, q interface{}, i interface{}) {229 collection.Find(q).One(i)230}231func ListByQ(collection *mgo.Collection, q interface{}, i interface{}) {232 collection.Find(q).All(i)233}234func ListByQLimit(collection *mgo.Collection, q interface{}, i interface{}, limit int) {235 collection.Find(q).Limit(limit).All(i)236}237// 查询某些字段, q是查询条件, fields是字段名列表238func GetByQWithFields(collection *mgo.Collection, q bson.M, fields []string, i interface{}) {239 selector := make(bson.M, len(fields))240 for _, field := range fields {241 selector[field] = true242 }243 collection.Find(q).Select(selector).One(i)244}245// 查询某些字段, q是查询条件, fields是字段名列表246func ListByQWithFields(collection *mgo.Collection, q bson.M, fields []string, i interface{}) {247 selector := make(bson.M, len(fields))248 for _, field := range fields {249 selector[field] = true250 }251 collection.Find(q).Select(selector).All(i)252}253func GetByIdAndUserId(collection *mgo.Collection, id, userId string, i interface{}) {254 collection.Find(GetIdAndUserIdQ(id, userId)).One(i)255}256func GetByIdAndUserId2(collection *mgo.Collection, id, userId bson.ObjectId, i interface{}) {257 collection.Find(GetIdAndUserIdBsonQ(id, userId)).One(i)258}259// 按field去重260func Distinct(collection *mgo.Collection, q bson.M, field string, i interface{}) {261 collection.Find(q).Distinct(field, i)262}263//----------------------264func Count(collection *mgo.Collection, q interface{}) int {265 cnt, err := collection.Find(q).Count()266 if err != nil {267 Err(err)268 }269 return cnt270}271func Has(collection *mgo.Collection, q interface{}) bool {272 if Count(collection, q) > 0 {273 return true274 }275 return false276}277//-----------------278// 得到主键和userId的复合查询条件279func GetIdAndUserIdQ(id, userId string) bson.M {280 return bson.M{"_id": bson.ObjectIdHex(id), "UserId": bson.ObjectIdHex(userId)}281}282func GetIdAndUserIdBsonQ(id, userId bson.ObjectId) bson.M {283 return bson.M{"_id": id, "UserId": userId}284}285// DB处理错误286func Err(err error) bool {287 if err != nil {288 fmt.Println(err)289 // 删除时, 查找290 if err.Error() == "not found" {291 return true292 }293 return false294 }295 return true296}...

Full Screen

Full Screen

mongodb.go

Source:mongodb.go Github

copy

Full Screen

...40}41func (m *MongoDB) Clone() *mgo.Session {42 return m.Session.Clone()43}44func (m *MongoDB) GetSession() *mgo.Session {45 if m.Session == nil {46 m.CreateSession(m.URL)47 }48 return m.Copy()49}50func (m *MongoDB) Run(collection string, s func(*mgo.Collection) error) error {51 session := m.GetSession()52 defer session.Close()53 c := session.DB("").C(collection)54 return s(c)55}56func (m *MongoDB) GetIter(collection string, s func(*mgo.Collection) *mgo.Query) *mgo.Iter {57 session := m.GetSession()58 defer session.Close()59 c := session.DB("").C(collection)60 return s(c).Iter()61}62// RunOnDatabase runs command on given database, instead of current database63func (m *MongoDB) RunOnDatabase(database, collection string, s func(*mgo.Collection) error) error {64 session := m.GetSession()65 defer session.Close()66 c := session.DB(database).C(collection)67 return s(c)68}69func (m *MongoDB) One(collection, id string, result interface{}) error {70 session := m.GetSession()71 defer session.Close()72 return session.DB("").C(collection).FindId(bson.ObjectIdHex(id)).One(result)73}74func (m *MongoDB) Iter(cl string, q func(*mgo.Collection) *mgo.Query, i func(*mgo.Iter) error) error {75 session := m.GetSession()76 defer session.Close()77 c := session.DB("").C(cl)78 var iter = q(c).Iter()79 var err = i(iter)80 if err != nil {81 return err82 }83 err = iter.Close()84 if err != nil {85 return err86 }87 if iter.Timeout() {88 return errors.New("iter timed out")89 }90 return nil91}92func (m *MongoDB) EnsureIndex(collection string, index mgo.Index) error {93 session := m.GetSession()94 defer session.Close()95 return session.DB("").C(collection).EnsureIndex(index)96}...

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import(2type Person struct{3}4func main(){5 session, err := mgo.Dial("localhost")6 if err != nil{7 panic(err)8 }9 defer session.Close()10 session.SetMode(mgo.Monotonic, true)11 c := session.DB("test").C("people")12 err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},13 &Person{"Cla", "+55 53 8402 8510"})14 if err != nil{15 panic(err)16 }17 result := Person{}18 err = c.Find(bson.M{"name": "Ale"}).One(&result)19 if err != nil{20 panic(err)21 }22 fmt.Println("Phone:", result.Phone)23}24import(25type Person struct{26}27func main(){28 session, err := mgo.Dial("localhost")29 if err != nil{30 panic(err)31 }32 defer session.Close()33 session.SetMode(mgo.Monotonic, true)34 c := session.DB("test").C("people")35 err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},36 &Person{"Cla", "+55 53 8402 8510"})37 if err != nil{38 panic(err)39 }40 result := Person{}41 iter := c.Find(bson.M{"name": "Ale"}).Iter()42 for iter.Next(&result){43 fmt.Println("Name:", result.Name)44 fmt.Println("Phone:", result.Phone)45 }46 if err := iter.Close(); err != nil{47 panic(err)48 }49}50import(51type Person struct{52}53func main(){54 session, err := mgo.Dial("localhost")55 if err != nil{56 panic(err)57 }58 defer session.Close()

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1func Get() (string, error) {2 session, err := mgo.Dial("localhost")3 if err != nil {4 panic(err)5 }6 defer session.Close()7 c := session.DB("database").C("collection")8 result := Data{}9 err = c.Find(bson.M{"key": "value"}).One(&result)10 if err != nil {11 }12}13func Insert(data string) error {14 session, err := mgo.Dial("localhost")15 if err != nil {16 panic(err)17 }18 defer session.Close()19 c := session.DB("database").C("collection")20 err = c.Insert(&Data{Data: data})21 if err != nil {22 }23}24func Update(data string) error {25 session, err := mgo.Dial("localhost")26 if err != nil {27 panic(err)28 }29 defer session.Close()30 c := session.DB("database").C("collection")31 err = c.Update(bson.M{"key": "value"}, bson.M{"$set": bson.M{"key": "value", "data": data}})32 if err != nil {33 }34}35func Remove() error {36 session, err := mgo.Dial("localhost")37 if err != nil {38 panic(err)39 }40 defer session.Close()41 c := session.DB("database").C("collection")42 err = c.Remove(bson.M{"key": "value"})43 if err != nil {44 }45}46func DropCollection() error {47 session, err := mgo.Dial("localhost")48 if err != nil {49 panic(err)50 }51 defer session.Close()52 c := session.DB("database").C("collection")

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1func Get() {2}3func Get() {4}5mgo.Get()6mgoObj := mgo.NewMgo()7mgoObj.Get()8import (9func main() {10 for _, filename := range os.Args[1:] {11 file, err := os.Open(filename)12 if err != nil {13 fmt.Fprintf(os.Stderr, "filecount: %v14 }15 countLines(file)16 file.Close()17 }18}19func countLines(file *os.File) {20 input := bufio.NewScanner(file)21 for input.Scan() {22 fmt.Println(input.Text())23 }24}25func main() {26 fmt.Println("Enter a string: ")27 fmt.Scan(&s1, &s2, &s3, &s4

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Keploy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful