예제 #1
0
//
// Returns all collections in database
//
func (d *Resource) DatabaseCollectionsHandler(req *restful.Request, resp *restful.Response) {
	// Mongo session
	session, needclose, err := d.SessMng.Get("local") //getParam("alias", req)
	if err != nil {
		WriteError(err, resp)
		return
	}
	if needclose {
		defer session.Close()
	}

	// Database request parameter
	dbname := "loudshout" //getParam("database", req)

	// 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)
}
예제 #2
0
//
// Returns all databases in alias
//
func (d *Resource) AliasDatabasesHandler(req *restful.Request, resp *restful.Response) {
	// filter invalids
	alias := getParam("alias", req)
	if alias == "" || strings.Index(alias, ".") != -1 {
		resp.WriteHeader(http.StatusBadRequest)
		return
	}

	// Mongo session
	session, needclose, err := d.SessMng.Get(alias)
	if err != nil {
		WriteError(err, resp)
		return
	}
	if needclose {
		defer session.Close()
	}

	// Get all databases in mongo
	names, err := session.DatabaseNames()
	if err != nil {
		WriteError(err, resp)
		return
	}

	// Write response back to client
	WriteResponse(names, resp)
}
예제 #3
0
// 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)
}
예제 #4
0
//
// 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/hiteshjoshi/mora/pull/31
	decoder := json.NewDecoder(req.Request.Body)
	log.Printf("Here %v", decoder)
	err := decoder.Decode(&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("local") //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
	}

	// Insert if request method is POST or no selector otherwise update
	if req.Request.Method == "POST" {
		d.handleInsert(col, selector, document, req, resp)
		return
	}

	d.handleUpdate(col, one, selector, document, req, resp)
}
예제 #5
0
//
// Removes document(/s) from collection
//
func (d *Resource) CollectionRemoveHandler(req *restful.Request, resp *restful.Response) {
	// Mongo session
	session, needclose, err := d.SessMng.Get("local") //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)
}
예제 #6
0
//
// Finds document(/s) in collection
//
func (d *Resource) CollectionFindHandler(req *restful.Request, resp *restful.Response) {
	// Mongo session
	session, needclose, err := d.SessMng.Get("local") //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)
}