Best Keploy code snippet using mgo.GetKeys
mongo_indexes_test.go
Source:mongo_indexes_test.go
1package server2import (3 "fmt"4 "net/http/httptest"5 "os"6 "path/filepath"7 "sort"8 "testing"9 "time"10 "github.com/gin-gonic/gin"11 "github.com/stretchr/testify/suite"12 "gopkg.in/mgo.v2"13 "gopkg.in/mgo.v2/dbtest"14)15var expectedIndexes = []mgo.Index{16 mgo.Index{Key: []string{"foo"}},17 mgo.Index{Key: []string{"-foo"}},18 mgo.Index{Key: []string{"bar.foo"}},19 mgo.Index{Key: []string{"-bar.foo"}},20 mgo.Index{Key: []string{"foo", "bar"}},21 mgo.Index{Key: []string{"bar", "foo", "-baz"}},22}23type MongoIndexesTestSuite struct {24 suite.Suite25 DBServer *dbtest.DBServer26 EST *time.Location27 Local *time.Location28 Session *mgo.Session29 Database *mgo.Database30 Engine *gin.Engine31 Server *httptest.Server32 Config Config33 FixtureID string34}35func (s *MongoIndexesTestSuite) SetupSuite() {36 s.EST = time.FixedZone("EST", -5*60*60)37 s.Local, _ = time.LoadLocation("Local")38 // Server configuration39 s.Config = DefaultConfig40 s.Config.DatabaseName = "fhir-test"41 s.Config.IndexConfigPath = "../fixtures/test_indexes.conf"42 // Create a temporary directory for the test database43 var err error44 err = os.Mkdir("./testdb", 0775)45 if err != nil {46 panic(err)47 }48 // setup the mongo database49 s.DBServer = &dbtest.DBServer{}50 s.DBServer.SetPath("./testdb")51 s.Session = s.DBServer.Session()52 s.Database = s.Session.DB(s.Config.DatabaseName)53 // Set gin to release mode (less verbose output)54 gin.SetMode(gin.ReleaseMode)55 // Build routes for testing56 s.Engine = gin.New()57 RegisterRoutes(s.Engine, make(map[string][]gin.HandlerFunc), NewMongoDataAccessLayer(s.Database), s.Config)58 // Create httptest server59 s.Server = httptest.NewServer(s.Engine)60}61func (s *MongoIndexesTestSuite) TearDownSuite() {62 s.Session.Close()63 s.DBServer.Wipe()64 s.DBServer.Stop()65 // remove the temporary database directory66 var err error67 err = removeContents("./testdb")68 if err != nil {69 panic(err)70 }71 err = os.Remove("./testdb")72 if err != nil {73 panic(err)74 }75}76func TestMongoIndexes(t *testing.T) {77 // bind test suite to go test78 suite.Run(t, new(MongoIndexesTestSuite))79}80func (s *MongoIndexesTestSuite) TestParseIndexStandardIndexAsc() {81 indexStr := "testcollection.foo_1"82 collectionName, index, err := parseIndex(indexStr)83 s.Nil(err, "Should return without error")84 s.Equal(collectionName, "testcollection", "Collection name should be 'testcollection'")85 s.Equal(len(index.Key), 1, "The created index should contain one key")86 s.Equal(index.Key[0], "foo", "The index key should be 'foo'")87 // We only need to check this once, since it's done for all successful indexes88 s.True(index.Background, "The index should be set to build in the background")89}90func (s *MongoIndexesTestSuite) TestParseIndexStandardIndexDesc() {91 indexStr := "testcollection.foo_-1"92 collectionName, index, err := parseIndex(indexStr)93 s.Nil(err, "Should return without error")94 s.Equal(collectionName, "testcollection", "Collection name should be 'testcollection'")95 s.Equal(len(index.Key), 1, "The created index should contain one key")96 s.Equal(index.Key[0], "-foo", "The index key should be '-foo'")97}98func (s *MongoIndexesTestSuite) TestParseIndexCompoundIndexAsc() {99 indexStr := "testcollection.(foo_1, bar_1)"100 collectionName, index, err := parseIndex(indexStr)101 s.Nil(err, "Should return without error")102 s.Equal(collectionName, "testcollection", "Collection name should be 'testcollection'")103 s.Equal(len(index.Key), 2, "The created index should contain 2 keys")104 s.Equal(index.Key[0], "foo", "The prefix index key should be 'foo'")105 s.Equal(index.Key[1], "bar", "The second index key should be 'bar'")106}107func (s *MongoIndexesTestSuite) TestParseIndexCompoundIndexDesc() {108 indexStr := "testcollection.(foo_-1, bar_-1)"109 collectionName, index, err := parseIndex(indexStr)110 s.Nil(err, "Should return without error")111 s.Equal(collectionName, "testcollection", "Collection name should be 'testcollection'")112 s.Equal(len(index.Key), 2, "The created index should contain 2 keys")113 s.Equal(index.Key[0], "-foo", "The prefix index key should be '-foo'")114 s.Equal(index.Key[1], "-bar", "The second index key should be '-bar'")115}116func (s *MongoIndexesTestSuite) TestParseIndexCompoundIndexMixed() {117 indexStr := "testcollection.(foo_-1, bar_1)"118 collectionName, index, err := parseIndex(indexStr)119 s.Nil(err, "Should return without error")120 s.Equal(collectionName, "testcollection", "Collection name should be 'testcollection'")121 s.Equal(len(index.Key), 2, "The created index should contain 2 keys")122 s.Equal(index.Key[0], "-foo", "The prefix index key should be '-foo'")123 s.Equal(index.Key[1], "bar", "The second index key should be 'bar'")124}125func (s *MongoIndexesTestSuite) TestParseIndexNoIndex() {126 indexStr := ""127 collectionName, index, err := parseIndex(indexStr)128 s.Equal(collectionName, "", "Collection name should be blank")129 s.Nil(index, "Index should be nil")130 s.NotNil(err, "Should return an error")131 s.Equal(err.Error(), "Index '' is invalid: Not of format <collection_name>.<index(es)>", "Unexpected error returned")132}133func (s *MongoIndexesTestSuite) TestParseIndexBadIndexFormat() {134 indexStr := "asdfasdf"135 collectionName, index, err := parseIndex(indexStr)136 s.Equal(collectionName, "", "Collection name should be blank")137 s.Nil(index, "Index should be nil")138 s.NotNil(err, "Should return an error")139 s.Equal(err.Error(), "Index 'asdfasdf' is invalid: Not of format <collection_name>.<index(es)>", "Unexpected error returned")140}141func (s *MongoIndexesTestSuite) TestParseIndexNoCollectionName() {142 indexStr := ".(foo_-1, bar_1)"143 collectionName, index, err := parseIndex(indexStr)144 s.Equal(collectionName, "", "Collection name should be blank")145 s.Nil(index, "Index should be nil")146 s.NotNil(err, "Should return an error")147 s.Equal(err.Error(), "Index '.(foo_-1, bar_1)' is invalid: No collection name given", "Unexpected error returned")148}149func (s *MongoIndexesTestSuite) TestParseIndexNoKeys() {150 indexStr := "testcollection."151 collectionName, index, err := parseIndex(indexStr)152 s.Equal(collectionName, "", "Collection name should be blank")153 s.Nil(index, "Index should be nil")154 s.NotNil(err, "Should return an error")155 s.Equal(err.Error(), "Index 'testcollection.' is invalid: No index key(s) given", "Unexpected error returned")156}157func (s *MongoIndexesTestSuite) TestParseIndexBadStandardKeyFormat() {158 indexStr := "testcollection.foo"159 collectionName, index, err := parseIndex(indexStr)160 s.Equal(collectionName, "", "Collection name should be blank")161 s.Nil(index, "Index should be nil")162 s.NotNil(err, "Should return an error")163 s.Equal(err.Error(), "Index 'testcollection.foo' is invalid: Standard key not of format: <key>_(-)1", "Unexpected error returned")164}165func (s *MongoIndexesTestSuite) TestParseIndexBadCompoundKeyFormat() {166 indexStr := "testcollection.(foobar"167 collectionName, index, err := parseIndex(indexStr)168 s.Equal(collectionName, "", "Collection name should be blank")169 s.Nil(index, "Index should be nil")170 s.NotNil(err, "Should return an error")171 s.Equal(err.Error(), "Index 'testcollection.(foobar' is invalid: Compound key not of format: (<key1>_(-)1, <key2>_(-)1, ...)", "Unexpected error returned")172}173func (s *MongoIndexesTestSuite) TestParseIndexBadCompoundKeySubKeyFormat() {174 indexStr := "testcollection.(foo, bar_1)"175 collectionName, index, err := parseIndex(indexStr)176 s.Equal(collectionName, "", "Collection name should be blank")177 s.Nil(index, "Index should be nil")178 s.NotNil(err, "Should return an error")179 s.Equal(err.Error(), "Index 'testcollection.(foo, bar_1)' is invalid: Compound key sub-key not of format: <key>_(-)1", "Unexpected error returned")180}181func (s *MongoIndexesTestSuite) TestConfigureIndexes() {182 // Configure test indexes183 indexSession := s.Session.Copy()184 ConfigureIndexes(indexSession, s.Config)185 indexSession.Close()186 // get the "testcollection" collection. This should have been auto-magically187 // created by ConfigureIndexes188 c := s.Database.C("testcollection")189 // get the indexes for this collection190 indexes, err := c.Indexes()191 if err != nil {192 panic(err)193 }194 // The indexes *should* be returned in the order they were created.195 // That's how they're returned by queries in the mongo shell at least.196 s.compareIndexes(expectedIndexes, indexes)197}198func (s *MongoIndexesTestSuite) TestConfigureIndexesNoConfigFile() {199 s.Config.IndexConfigPath = "./does_not_exist.conf"200 indexSession := s.Session.Copy()201 s.NotPanics(func() { ConfigureIndexes(indexSession, s.Config) }, "Should not panic if no config file is found")202 indexSession.Close()203}204func (s *MongoIndexesTestSuite) compareIndexes(expected, actual []mgo.Index) {205 for _, idx := range actual {206 s.True(len(idx.Key) > 0, "Index should have at least 1 key")207 if idx.Key[0] == "_id" {208 // Skip testing the indexes created by the system209 continue210 }211 s.True(indexInSlice(expected, idx), fmt.Sprintf("Index testcollection: %s was not parsed correctly", idx.Key[0]))212 }213}214func indexInSlice(indexesSlice []mgo.Index, want mgo.Index) bool {215 // Compares two indexes by Key only216 if len(want.Key) > 0 {217 for _, idx := range indexesSlice {218 if want.Key[0] == idx.Key[0] {219 return true220 }221 }222 }223 return false224}225func removeContents(dir string) error {226 d, err := os.Open(dir)227 if err != nil {228 return err229 }230 defer d.Close()231 names, err := d.Readdirnames(-1)232 if err != nil {233 return err234 }235 for _, name := range names {236 err = os.RemoveAll(filepath.Join(dir, name))237 if err != nil {238 return err239 }240 }241 return nil242}243// getKeys returns a slice of all keys in an IndexMap in sorted order244func getKeys(keyMap IndexMap) []string {245 keys := make([]string, len(keyMap))246 var i = 0247 for k := range keyMap {248 keys[i] = k249 i++250 }251 sort.Strings(keys)252 return keys253}...
mgowrapper.go
Source:mgowrapper.go
1package mgohttp2import (3 "context"4 "fmt"5 "strings"6 opentracing "github.com/opentracing/opentracing-go"7 opentracinglog "github.com/opentracing/opentracing-go/log"8 mgo "gopkg.in/mgo.v2"9 bson "gopkg.in/mgo.v2/bson"10)11type tracedMgoSession struct {12 sess *mgo.Session13 ctx context.Context14}15func (ts tracedMgoSession) DB(name string) MongoDatabase {16 sp := opentracing.SpanFromContext(ts.ctx)17 sp.SetTag("db-name", name)18 return tracedMgoDatabase{19 db: ts.sess.DB(name),20 ctx: opentracing.ContextWithSpan(ts.ctx, sp),21 }22}23func (ts tracedMgoSession) Ping() error {24 sp, _ := opentracing.StartSpanFromContext(ts.ctx, "ping")25 defer sp.Finish()26 return logAndReturnErr(sp, ts.sess.Ping())27}28type tracedMgoDatabase struct {29 db *mgo.Database30 ctx context.Context31}32func (t tracedMgoDatabase) C(collection string) MongoCollection {33 return tracedMgoCollection{34 collectionName: collection,35 collection: t.db.C(collection),36 ctx: t.ctx,37 }38}39func (t tracedMgoDatabase) Run(cmd interface{}, result interface{}) error {40 sp, _ := opentracing.StartSpanFromContext(t.ctx, "run")41 defer sp.Finish()42 sp.LogKV(opentracinglog.String("cmd", fmt.Sprintf("%#v", cmd)))43 return logAndReturnErr(sp, t.db.Run(cmd, result))44}45type tracedMgoCollection struct {46 collectionName string47 collection *mgo.Collection48 ctx context.Context49}50func (tc tracedMgoCollection) UpdateId(id bson.ObjectId, update interface{}) error {51 return tc.Update(bson.M{"_id": id}, update)52}53func (tc tracedMgoCollection) Update(selector interface{}, update interface{}) error {54 sp, _ := opentracing.StartSpanFromContext(tc.ctx, "update")55 sp.SetTag("collection", tc.collectionName)56 sp.LogFields(bsonToKeys("selector", selector))57 sp.LogFields(bsonToKeys("update", update))58 defer sp.Finish()59 return logAndReturnErr(sp, tc.collection.Update(selector, update))60}61func (tc tracedMgoCollection) UpdateAll(selector interface{}, update interface{}) (info *mgo.ChangeInfo, err error) {62 sp, _ := opentracing.StartSpanFromContext(tc.ctx, "update-all")63 sp.SetTag("collection", tc.collectionName)64 sp.LogFields(bsonToKeys("selector", selector))65 sp.LogFields(bsonToKeys("update", update))66 defer sp.Finish()67 info, err = tc.collection.UpdateAll(selector, update)68 return info, logAndReturnErr(sp, err)69}70func (tc tracedMgoCollection) Insert(docs ...interface{}) (err error) {71 sp, _ := opentracing.StartSpanFromContext(tc.ctx, "insert")72 sp.LogFields(opentracinglog.Int("num-docs", len(docs)))73 defer sp.Finish()74 return logAndReturnErr(sp, tc.collection.Insert(docs...))75}76func (tc tracedMgoCollection) Upsert(selector interface{}, update interface{}) (info *mgo.ChangeInfo, err error) {77 sp, _ := opentracing.StartSpanFromContext(tc.ctx, "upsert")78 sp.LogFields(bsonToKeys("selector", selector))79 sp.LogFields(bsonToKeys("update", update))80 defer sp.Finish()81 info, err = tc.collection.Upsert(selector, update)82 return info, logAndReturnErr(sp, err)83}84func (tc tracedMgoCollection) FindId(id bson.ObjectId) MongoQuery {85 return tc.Find(bson.M{"_id": id})86}87func (tc tracedMgoCollection) Find(selector interface{}) MongoQuery {88 sp, ctx := opentracing.StartSpanFromContext(tc.ctx, "find")89 sp.SetTag("collection", tc.collectionName)90 // NOTE: Find just starts the trace, the finishing call on the MongoQuery must91 // finish it.92 sp.LogFields(bsonToKeys("selector", selector))93 return tracedMongoQuery{94 q: tc.collection.Find(selector),95 ctx: ctx,96 }97}98func (tc tracedMgoCollection) RemoveId(id bson.ObjectId) error {99 return tc.Remove(bson.M{"_id": id})100}101func (tc tracedMgoCollection) Remove(selector interface{}) error {102 sp, _ := opentracing.StartSpanFromContext(tc.ctx, "remove")103 sp.SetTag("collection", tc.collectionName)104 sp.LogFields(bsonToKeys("selector", selector))105 defer sp.Finish()106 return logAndReturnErr(sp, tc.collection.Remove(selector))107}108func (tc tracedMgoCollection) RemoveAll(selector interface{}) (info *mgo.ChangeInfo, err error) {109 sp, _ := opentracing.StartSpanFromContext(tc.ctx, "removeall")110 sp.SetTag("collection", tc.collectionName)111 sp.LogFields(bsonToKeys("selector", selector))112 defer sp.Finish()113 info, err = tc.collection.RemoveAll(selector)114 return info, logAndReturnErr(sp, err)115}116type tracedMongoQuery struct {117 q *mgo.Query118 ctx context.Context119}120func (q tracedMongoQuery) All(result interface{}) error {121 sp := opentracing.SpanFromContext(q.ctx)122 defer sp.Finish()123 sp.SetTag("access-method", "All")124 return logAndReturnErr(sp, q.q.All(result))125}126func (q tracedMongoQuery) One(result interface{}) (err error) {127 sp := opentracing.SpanFromContext(q.ctx)128 defer sp.Finish()129 sp.SetTag("access-method", "One")130 return logAndReturnErr(sp, q.q.One(result))131}132func (q tracedMongoQuery) Count() (int, error) {133 sp := opentracing.SpanFromContext(q.ctx)134 defer sp.Finish()135 sp.SetTag("access-method", "Count")136 n, err := q.q.Count()137 return n, logAndReturnErr(sp, err)138}139func (q tracedMongoQuery) Limit(n int) MongoQuery {140 // NOTE: this function just modifies the query, we will rely on141 // One/All to terminate the span.142 sp := opentracing.SpanFromContext(q.ctx)143 sp.LogFields(opentracinglog.Int("query-limit", n))144 return tracedMongoQuery{145 q: q.q.Limit(n),146 ctx: opentracing.ContextWithSpan(q.ctx, sp),147 }148}149func (q tracedMongoQuery) Select(selector interface{}) MongoQuery {150 // NOTE: this function just modifies the query, we will rely on151 // One/All to terminate the span.152 sp := opentracing.SpanFromContext(q.ctx)153 sp.LogFields(bsonToKeys("select", selector))154 return tracedMongoQuery{155 q: q.q.Select(selector),156 ctx: opentracing.ContextWithSpan(q.ctx, sp),157 }158}159func (q tracedMongoQuery) Hint(indexKey ...string) MongoQuery {160 // NOTE: this function just modifies the query, we will rely on161 // One/All to terminate the span.162 sp := opentracing.SpanFromContext(q.ctx)163 for i, hint := range indexKey {164 sp.LogFields(opentracinglog.String(fmt.Sprintf("hint.%d", i), hint))165 }166 return tracedMongoQuery{167 q: q.q.Hint(indexKey...),168 ctx: opentracing.ContextWithSpan(q.ctx, sp),169 }170}171func (q tracedMongoQuery) Sort(fields ...string) MongoQuery {172 // NOTE: this function just modifies the query, we will rely on173 // One/All to terminate the span.174 sp := opentracing.SpanFromContext(q.ctx)175 sp.SetTag("sort", strings.Join(fields, "|"))176 return tracedMongoQuery{177 q: q.q.Sort(fields...),178 ctx: opentracing.ContextWithSpan(q.ctx, sp),179 }180}181func (q tracedMongoQuery) Apply(change mgo.Change, result interface{}) (info *mgo.ChangeInfo, err error) {182 sp := opentracing.SpanFromContext(q.ctx)183 defer sp.Finish()184 sp.SetTag("access-method", "apply")185 sp.LogFields(bsonToKeys("update", change.Update))186 sp.LogFields(187 opentracinglog.Bool("remove", change.Remove),188 opentracinglog.Bool("return-new", change.ReturnNew),189 opentracinglog.Bool("upsert", change.Upsert),190 )191 info, err = q.q.Apply(change, result)192 return info, logAndReturnErr(sp, err)193}194func (q tracedMongoQuery) Iter() MongoIter {195 _, ctx := opentracing.StartSpanFromContext(q.ctx, "iter")196 return tracedMongoIter{197 i: q.q.Iter(),198 ctx: ctx,199 }200}201type tracedMongoIter struct {202 i *mgo.Iter203 ctx context.Context204}205func (t tracedMongoIter) All(result interface{}) error {206 sp, _ := opentracing.StartSpanFromContext(t.ctx, "iter-all")207 defer sp.Finish()208 return logAndReturnErr(sp, t.i.All(result))209}210func (t tracedMongoIter) Close() error {211 sp := opentracing.SpanFromContext(t.ctx)212 defer sp.Finish()213 return logAndReturnErr(sp, t.i.Close())214}215func (t tracedMongoIter) Done() bool {216 return t.i.Done()217}218func (t tracedMongoIter) Err() error {219 return logAndReturnErr(opentracing.SpanFromContext(t.ctx), t.i.Err())220}221func (t tracedMongoIter) Next(result interface{}) bool {222 sp, _ := opentracing.StartSpanFromContext(t.ctx, "iter-next")223 defer sp.Finish()224 return t.i.Next(result)225}226// logAndReturnErr is a tiny helper for adding the error to a log inline.227func logAndReturnErr(sp opentracing.Span, err error) error {228 sp.LogFields(opentracinglog.Error(err))229 return err230}231func getKeys(prefix string, q bson.M) []string {232 addPrefix := func(s string) string {233 if prefix == "" {234 return s235 }236 return prefix + "." + s237 }238 fields := []string{}239 for k, v := range q {240 switch val := v.(type) {241 case bson.M:242 fields = append(fields, getKeys(addPrefix(k), val)...)243 default:244 fields = append(fields, addPrefix(k))245 }246 }247 return fields248}249// bsonToKeys transforms an arbitrary mgo arg into a set of log fields.250// This is mostly geared towards bson.M, but the Sprintf fallback should handle arrays251// sufficiently for tracing purposes.252func bsonToKeys(name string, query interface{}) opentracinglog.Field {253 queryFields := []string{}254 if q, ok := query.(bson.M); ok {255 queryFields = getKeys("", q)256 }257 return opentracinglog.String(name, strings.Join(queryFields, "|"))258}...
main.go
Source:main.go
1package main2import (3 "fmt"4 "log"5 "net/http"6 "os"7 "strings"8 "time"9 "labix.org/v2/mgo"10 "labix.org/v2/mgo/bson"11)12type Dataset struct {13 CreatorDisplayName string `bson:"creatorDisplayName"`14 CreatorShortName string `bson:"creatorShortName"`15 DisplayName string `bson:"displayName"`16 User string `bson:"user"`17 Tool string `bson:"tool"`18 State string `bson:"state"`19 BoxServer string `bson:"boxServer"`20}21type User struct {22 ShortName string `bson:"shortName"`23 CanBeReally []string `bson:"canBeReally"`24 SshKeys []string `bson:"sshKeys"`25}26type Box struct {27 Name string `bson:"name"`28 Server string `bson:"server"`29 Uid uint32 `bson:"uid"`30 Users []string `bson:"users"`31}32func check(err error) {33 if err != nil {34 panic(err)35 }36}37func MatchAny(what string, values ...string) bson.M {38 var query []bson.M39 for _, value := range values {40 query = append(query, bson.M{what: value})41 }42 return bson.M{"$or": query}43}44// Obtain list of users allowed to access a box (directly specified in Box struct)45func usersFromBox(db *mgo.Database, boxName string) (users []string) {46 x := db.C("boxes").Find(MatchAny("name", boxName))47 var result []Box48 err := x.All(&result)49 check(err)50 users = []string{}51 for _, b := range result {52 for _, user := range b.Users {53 users = append(users, user)54 }55 }56 return users57}58// Looking through canBeReally, find all SSH keys for all `usernames`.59// Makes as many queries as necessary according to the depth of the canBeReally60// tree, pruning duplicates.61func allKeysFromUsernames(db *mgo.Database, usernames []string) []string {62 seenSet := map[string]struct{}{}63 isSeen := func(u string) bool {64 _, ok := seenSet[u]65 return ok66 }67 extendSeenSet := func(us []string) {68 for _, u := range us {69 seenSet[u] = struct{}{}70 }71 }72 allKeys := []string{}73 for len(usernames) > 0 {74 toQuery := usernames75 extendSeenSet(toQuery)76 usernames = []string{}77 var matchingUsers []User78 err := db.C("users").Find(MatchAny("shortName", toQuery...)).All(&matchingUsers)79 if err != nil {80 log.Printf("Error querying users: %q -- us:%q", err, toQuery)81 }82 for _, user := range matchingUsers {83 for _, nextUser := range user.CanBeReally {84 if !isSeen(nextUser) {85 usernames = append(usernames, nextUser)86 }87 }88 allKeys = append(allKeys, fmt.Sprintf("# From user:%s", user.ShortName))89 allKeys = append(allKeys, user.SshKeys...)90 }91 }92 return allKeys93}94// Get usernames of all staff95func getStaff(db *mgo.Database) []string {96 usersQ := db.C("users").Find(map[string]bool{"isStaff": true})97 var matchingUsers []User98 usersQ.All(&matchingUsers)99 users := []string{}100 for _, u := range matchingUsers {101 users = append(users, u.ShortName)102 }103 return users104}105// Merge two lists keeping only the uniques106func combineUsers(a, b []string) []string {107 both := append(a, b...)108 allowedUsers := map[string]struct{}{}109 for _, u := range both {110 allowedUsers[u] = struct{}{}111 }112 combined := []string{}113 for u := range allowedUsers {114 combined = append(combined, u)115 }116 return combined117}118// Get the list of all SSH keys allowed to access a box.119func getKeys(session *mgo.Session, boxname string) (boxUsers, usernames []string, keys string) {120 this_session := session.Clone()121 defer this_session.Close()122 db := this_session.DB("")123 staff := getStaff(db)124 boxUsers = usersFromBox(db, boxname)125 usernames = combineUsers(staff, boxUsers) // returned126 // Looks through `canBeReally`.127 keySlice := allKeysFromUsernames(db, usernames)128 for _, k := range keySlice {129 k = strings.Replace(k, "\n", "", -1)130 if !strings.HasPrefix(k, "ssh-") && !strings.HasPrefix(k, "#") {131 keys += "# NOT VAILD: "132 }133 keys += k + "\n"134 }135 return136}137// Serve sshkeys at http://:33845/{boxname}138func main() {139 defer func() {140 if err := recover(); err != nil {141 panic(err)142 }143 }()144 var session *mgo.Session145 var err error146 go func() {147 for session == nil {148 log.Println("Connecting to mongo..")149 session, err = mgo.Dial(os.Getenv("CU_DB"))150 if err != nil {151 if session != nil {152 session.Close()153 session = nil154 }155 log.Printf("Database connection failed (%q), retrying..", err)156 time.Sleep(10 * time.Second)157 }158 }159 log.Println("Connected to mongo.")160 }()161 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {162 u := r.URL.Path[1:]163 if session == nil {164 log.Printf("%v StatusServiceUnavailable session == nil", u)165 w.WriteHeader(http.StatusServiceUnavailable)166 return167 }168 boxUsers, allUsers, keys := getKeys(session, u)169 log.Printf("%s:%v:%q:%q", u, strings.Count(keys, "\n"), boxUsers, allUsers)170 fmt.Fprint(w, keys)171 })172 log.Println("Serving..")173 err = http.ListenAndServe("localhost:33845", nil)174 check(err)175}...
GetKeys
Using AI Code Generation
1import (2func main() {3 orm.RegisterDriver("mongo", orm.DR_Mongo)4 if err != nil {5 panic(err)6 }7 session.SetMode(mgo.Monotonic, true)8 c := session.DB("test").C("test")9 count, err := c.Find(bson.M{"name": "Foo"}).Count()10 if err != nil {11 panic(err)12 }13 fmt.Println("Count: ", count)14 iter := c.Find(bson.M{"name": "Foo"}).Iter()15 result := bson.M{}16 for iter.Next(&result) {17 fmt.Println("Result: ", result)18 }19 if err := iter.Close(); err != nil {20 panic(err)21 }22 beego.Run()23}24import (25func GetKeys() []string {26 o := orm.NewOrm()27 o.Using("default")28 session := o.(*orm.MongoDriver).GetSession().Copy()29 defer session.Close()30 c := session.DB("test").C("test")31 c.Find(nil).Distinct("name", &keys)32}33import (34type MainController struct {35}36func (c *MainController) Get() {
GetKeys
Using AI Code Generation
1import (2type User struct {3}4func init() {5 session, err = mgo.Dial("localhost")6 if err != nil {7 panic(err)8 }9}10func main() {11 db := session.DB("test")12 c := db.C("user")13 index := mgo.Index{14 Key: []string{"first_name", "last_name"},15 }16 err := c.EnsureIndex(index)17 if err != nil {18 panic(err)19 }20 err = c.Insert(&User{FirstName: "John", LastName: "Smith"}, &User{FirstName: "John", LastName: "Doe"})21 if err != nil {22 panic(err)23 }24 info, err := c.Indexes()25 if err != nil {26 panic(err)27 }28 for _, index := range info {29 fmt.Println(index)30 }31 keys, err := c.IndexKeys()32 if err != nil {33 panic(err)34 }35 for _, key := range keys {36 fmt.Println(key)37 }38}39import (40type User struct {
GetKeys
Using AI Code Generation
1import (2func main() {3 fmt.Println("code to use GetKeys method of mgo class")4 fmt.Println("code to use GetKeys method of mgo class")5 fmt.Println("code to use GetKeys method of mgo class")6}7import (8func main() {9 fmt.Println("code to use GetKeys method of mgo class")10 fmt.Println("code to use GetKeys method of mgo class")11 fmt.Println("code to use GetKeys method of mgo class")12}13import (14func main() {15 fmt.Println("code to use GetKeys method of mgo class")16 fmt.Println("code to use GetKeys method of mgo class")17 fmt.Println("code to use GetKeys method of mgo class")18}19func GetKeys() {20 fmt.Println("GetKeys of mgo class")21}22import (23func main() {24 fmt.Println("code to use GetKeys method of mgo class")25 fmt.Println("code to use GetKeys method of mgo class")26 fmt.Println("code to use GetKeys method of mgo class")27}28I want to know how to import the "mgo" package into "1.go", "2.go" and "3.go" so that I can use
GetKeys
Using AI Code Generation
1import (2func main() {3 var mgoObj = mgo.Mgo{}4 var result = mgoObj.GetKeys(db, collection, key, value)5 fmt.Println(result)6}7import (8func main() {9 var mgoObj = mgo.Mgo{}10 var result = mgoObj.GetKeys(db, collection, key, value)11 fmt.Println(result)12}13import (14func main() {15 var mgoObj = mgo.Mgo{}16 var result = mgoObj.GetKeys(db, collection, key, value)17 fmt.Println(result)18}19import (20func main() {21 var mgoObj = mgo.Mgo{}22 var result = mgoObj.GetKeys(db, collection, key, value)23 fmt.Println(result)24}25import (26func main() {
GetKeys
Using AI Code Generation
1func GetKeys() []string {2 session, err := mgo.Dial("localhost")3 if err != nil {4 panic(err)5 }6 defer session.Close()7 c := session.DB("test").C("test")8 iter := c.Find(nil).Iter()9 result := bson.M{}10 for iter.Next(&result) {11 for k, _ := range result {12 keys = append(keys, k)13 }14 }15}16func GetKeys() []string {17 session, err := mgo.Dial("localhost")18 if err != nil {19 panic(err)20 }21 defer session.Close()22 c := session.DB("test").C("test")23 iter := c.Find(nil).Iter()24 result := bson.M{}25 for iter.Next(&result) {26 for k, _ := range result {27 keys = append(keys, k)28 }29 }30}31func GetKeys() []string {32 session, err := mgo.Dial("localhost")33 if err != nil {34 panic(err)35 }36 defer session.Close()37 c := session.DB("test").C("test")38 iter := c.Find(nil).Iter()39 result := bson.M{}40 for iter.Next(&result) {41 for k, _ := range result {42 keys = append(keys, k)43 }44 }45}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!