// // Returns all collections in database // func (d *Resource) DatabaseCollectionsHandler(req *restful.Request, resp *restful.Response) { // Mongo session session, needclose, err := d.SessMng.Get(getParam("alias", req)) //先查服务器 if err != nil { WriteError(err, resp) return } if needclose { defer session.Close() } // Database request parameter dbname := getParam("database", req) //再拿到数据库信息 println(dbname) // Get collections from database collections, err := session.DB(dbname).CollectionNames() //拿到数据库下所有的集合 if err != nil { WriteError(err, resp) return } if collections == nil { err = errors.New("Unknown database: " + dbname) WriteError(err, resp) return } // Write collections back to client WriteResponse(collections, resp) }
// // Returns all databases in alias // func (d *Resource) AliasDatabasesHandler(req *restful.Request, resp *restful.Response) { // filter invalids alias := getParam("alias", req) //先拿到alias,也就是配置文件中的服务器信息 println(alias) if alias == "" || strings.Index(alias, ".") != -1 { resp.WriteHeader(http.StatusBadRequest) return } // Mongo session session, needclose, err := d.SessMng.Get(alias) //通过SessionManager拿到指定的alias所对应的session if err != nil { WriteError(err, resp) return } if needclose { defer session.Close() } // Get all databases in mongo names, err := session.DatabaseNames() //查询当前服务器的所有Databases if err != nil { WriteError(err, resp) return } // Write response back to client WriteResponse(names, resp) }
// GET http://localhost:8181/stats/local/landskape/systems func (s *Resource) CollectionStatisticsHandler(req *restful.Request, resp *restful.Response) { // Mongo session session, needsClose, err := s.SessMng.Get(req.PathParameter("alias")) if err != nil { WriteError(err, resp) return } if needsClose { defer session.Close() } var ( // Request parameters collection = req.PathParameter("collection") database = req.PathParameter("database") // Statistics result result = bson.M{} ) // Get statistics for collection err = session.DB(database).Run(bson.M{"collStats": collection, "scale": 1}, &result) if err != nil { WriteError(err, resp) return } // Write result to console fmt.Printf("stats result:%#v", result) // Write result back to client WriteResponse(result, resp) }
// // Updates or inserts document(/s) in collection. // Depending on request method // POST - insert // PUT - update // func (d *Resource) CollectionUpdateHandler(req *restful.Request, resp *restful.Response) { // Read a document from request document := bson.M{} // Handle JSON parsing manually here, instead of relying on go-restful's // req.ReadEntity. This is because ReadEntity currently parses JSON with // UseNumber() which turns all numbers into strings. See: // https://github.com/emicklei/mora/pull/31 decoder := json.NewDecoder(req.Request.Body) err := decoder.Decode(&document) //将body赋值给document if err != nil { WriteStatusError(http.StatusBadRequest, err, resp) return } document, err = mejson.Unmarshal(document) if err != nil { WriteStatusError(http.StatusBadRequest, err, resp) return } // Mongo session session, needclose, err := d.SessMng.Get(getParam("alias", req)) if err != nil { WriteError(err, resp) return } // Close session if it's needed if needclose { defer session.Close() } // Mongo Collection col := d.GetMongoCollection(req, session) // Compose a selector from request selector, one, err := getSelector(req) if err != nil { WriteError(err, resp) return } //isStrict := getParam("strict", req) // Insert if request method is POST or no selector otherwise update if req.Request.Method == "POST" { //如果是PUT请求,那么则新增 d.handleInsert(col, selector, document, req, resp) return } //否则,就更新 d.handleUpdate(col, one, selector, document, req, resp) }
// // Removes document(/s) from collection // func (d *Resource) CollectionRemoveHandler(req *restful.Request, resp *restful.Response) { // Mongo session session, needclose, err := d.SessMng.Get(getParam("alias", req)) if err != nil { WriteError(err, resp) return } // Close session if it's needed if needclose { defer session.Close() } // Mongo Collection col := d.GetMongoCollection(req, session) // Compose a selector from request // Get selector from `_id` path parameter and `query` query parameter selector, one, err := getSelector(req) if err != nil { WriteError(err, resp) return } // If no selector at all - drop entire collection if len(selector) == 0 { err = col.DropCollection() if err != nil { WriteError(err, resp) return } WriteSuccess(resp) return } // Remove one document if no query, otherwise remove all matching query if one { err = col.Remove(selector) } else { _, err = col.RemoveAll(selector) } if err != nil { WriteError(err, resp) return } // Write success response WriteSuccess(resp) }
// // Finds document(/s) in collection // func (d *Resource) CollectionFindHandler(req *restful.Request, resp *restful.Response) { // Mongo session session, needclose, err := d.SessMng.Get(getParam("alias", req)) if err != nil { WriteError(err, resp) return } // Close session if it's needed if needclose { defer session.Close() } // Mongo Collection col := d.GetMongoCollection(req, session) // Compose a query from request query, one, err := d.ComposeQuery(col, req) if err != nil { WriteStatusError(400, err, resp) return } // If _id parameter is included in path // queries only one document. // Get documents from database if one { // Get one document document := bson.M{} err = query.One(&document) if err != nil { WriteError(err, resp) return } var jsonDocument interface{} if req.QueryParameter("extended_json") == "true" { jsonDocument, err = mejson.Marshal(document) if err != nil { WriteError(err, resp) return } } else { jsonDocument = document } WriteResponse(jsonDocument, resp) return } // Get all documents documents := []bson.M{} err = query.All(&documents) if err != nil { WriteError(err, resp) return } var jsonDocuments interface{} if req.QueryParameter("extended_json") == "true" { jsonDocuments, err = mejson.Marshal(documents) if err != nil { WriteError(err, resp) return } } else { jsonDocuments = documents } res := struct { Success bool `json:"success"` Count interface{} `json:"count,omitempty"` Prev string `json:"prev_url,omitempty"` Next string `json:"next_url,omitempty"` Data interface{} `json:"data"` }{Success: true, Data: jsonDocuments} // Get limit amount limitnum := 10 if limit := req.QueryParameter("limit"); len(limit) > 0 { limitnum, _ = strconv.Atoi(limit) } // If got full limit set next link if len(documents) == limitnum { res.Prev, res.Next = d.prevnexturl(req) } // Count documents if count parameter is included in query if c, _ := strconv.ParseBool(req.QueryParameter("count")); c { query.Skip(0) query.Limit(0) if n, err := query.Count(); err == nil { res.Count = n resp.AddHeader("X-Object-Count", strconv.Itoa(n)) } } // Write result back to client resp.WriteEntity(res) }