本文整理汇总了Golang中gopkg/in/mgo/v2/bson.IsObjectIdHex函数的典型用法代码示例。如果您正苦于以下问题:Golang IsObjectIdHex函数的具体用法?Golang IsObjectIdHex怎么用?Golang IsObjectIdHex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsObjectIdHex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getTicket
func getTicket(db *mgo.Database, boardIDHex, ticketIDHex string) (
*models.Ticket, *APIError,
) {
if !bson.IsObjectIdHex(boardIDHex) || !bson.IsObjectIdHex(ticketIDHex) {
return nil, &APIError{
"Both 'board_id' and 'ticket_id' must be a valid 'ObjectIDs'",
http.StatusBadRequest}
}
var (
ticket = models.Ticket{}
ticketQuery = db.C("tickets").Find(bson.M{
"_id": bson.ObjectIdHex(ticketIDHex),
"board_id": bson.ObjectIdHex(boardIDHex),
})
)
if err := ticketQuery.One(&ticket); err != nil {
if err == mgo.ErrNotFound {
return nil, &APIError{"Ticket not found", http.StatusNotFound}
}
return nil, &APIError{err.Error(), http.StatusInternalServerError}
}
return &ticket, nil
}
示例2: DeleteSubmission
// DeleteSubmission deletes a submission as well as updating a form's stats.
func DeleteSubmission(context interface{}, db *db.DB, id, formID string) error {
log.Dev(context, "DeleteSubmission", "Started : Submission[%s]", id)
if !bson.IsObjectIdHex(id) {
log.Error(context, "DeleteSubmission", ErrInvalidID, "Completed")
return ErrInvalidID
}
if !bson.IsObjectIdHex(formID) {
log.Error(context, "Delete", ErrInvalidID, "Completed")
return ErrInvalidID
}
if err := submission.Delete(context, db, id); err != nil {
log.Error(context, "DeleteSubmission", err, "Completed")
return err
}
if _, err := form.UpdateStats(context, db, formID); err != nil {
log.Error(context, "DeleteSubmission", err, "Completed")
return err
}
log.Dev(context, "DeleteSubmission", "Started")
return nil
}
示例3: SavePerson
func SavePerson(p *Person) {
c := getCollection()
log.Printf("Saving person: %s", p.Id.Hex())
log.Printf("Person has valid objectid: %s", bson.IsObjectIdHex(p.Id.Hex()))
// Does the object exist?
if !bson.IsObjectIdHex(p.Id.Hex()) {
p.Id = bson.NewObjectId()
err := c.Insert(p)
log.Printf("Inserted person: %v", p.Id)
if err != nil {
log.Panic("Error whilst inserting person: %v", err)
}
} else {
err := c.UpdateId(p.Id, p)
log.Printf("Saved person: %v", p.Id)
if err != nil {
log.Panic("Error whilst updating person: %v", err)
}
}
}
示例4: IsMyFile
// 是否是我的文件
func (this *FileService) IsMyFile(userId, fileId string) bool {
// 如果有问题会panic
if !bson.IsObjectIdHex(fileId) || !bson.IsObjectIdHex(userId) {
return false
}
return db.Has(db.Files, bson.M{"UserId": bson.ObjectIdHex(userId), "_id": bson.ObjectIdHex(fileId)})
}
示例5: DelAdmin
// DelAdmin removes a member from an existing group
func DelAdmin(c *echo.Context) (int, interface{}) {
digitsID, ok := c.Get("digitsID").(int64)
if !ok {
return msg.Forbidden("session required")
}
// Get group id and convert from string to objectId
rawMID := c.Param("mid")
if !bson.IsObjectIdHex(rawMID) {
return msg.BadRequest("bad id: not a ObjectId")
}
// find the group
memberID := bson.ObjectIdHex(rawMID)
// Get group id and convert from string to objectId
rawGID := c.Param("gid")
if !bson.IsObjectIdHex(rawGID) {
return msg.BadRequest("bad id: not a ObjectId")
}
// find the group
groupID := bson.ObjectIdHex(rawGID)
err := mangos.Update(constants.CGroups, bson.M{
"$and": []bson.M{
bson.M{"_id": groupID},
bson.M{"admins": digitsID},
},
}, bson.M{"$pull": bson.M{"admins": memberID}})
if err != nil {
return msg.InternalError(err)
}
return msg.Ok("deleted admin")
}
示例6: Plan
func (loccontroller Controller) Plan(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
var detail RoutePlan
arr := make([]Cordnts, 0)
var map1 map[string]Cordnts
map1 = make(map[string]Cordnts)
json.NewDecoder(request.Body).Decode(&detail)
if !bson.IsObjectIdHex(detail.Strt_locid) {
writer.WriteHeader(400)
return
}
strtpt = detail.Strt_locid
strtid := bson.ObjectIdHex(detail.Strt_locid)
if err := loccontroller.session.DB("jaspalgill").C("locations").FindId(strtid).One(&intLoc); err != nil {
writer.WriteHeader(400)
return
}
var bstroute BestRoute
iniCordnts.Latitude = intLoc.Coordinate.Latitude
iniCordnts.Longitude = intLoc.Coordinate.Longitude
for l := 0; l < len(detail.Loc_id); l++ {
id := detail.Loc_id[l]
if !bson.IsObjectIdHex(id) {
writer.WriteHeader(400)
return
} else {
nid := bson.ObjectIdHex(id)
var locatn Loc
if err := loccontroller.session.DB("jaspalgill").C("locations").FindId(nid).One(&locatn); err != nil {
writer.WriteHeader(400)
return
} else {
var cordnt Cordnts
cordnt.Latitude = locatn.Coordinate.Latitude
cordnt.Longitude = locatn.Coordinate.Longitude
map1[detail.Loc_id[l]] = cordnt
arr = append(arr, cordnt)
}
}
}
Loop(iniCordnts, arr, map1)
bstroute.id = bson.NewObjectId()
bstroute.stats = "planning"
bstroute.totldst = totldst
bstroute.total_cost = totlcost
bstroute.total_dur = totldur
bstroute.Strt_locid = strtpt
bstroute.bstroute_locid = bstRout
loccontroller.session.DB("jaspalgill").C("cmpe273").Insert(bstroute)
jsn, _ := json.Marshal(bstroute)
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(200)
fmt.Fprintf(writer, "%sess", jsn)
}
示例7: HandleFeedItem
/*
* Handle all inbound websocket messages. This is where all payments and purchases
* are given to the back-end, to be processed appropriately. There is no need for
* this handle function to return a value to the webserver, because the webserver
* rebroadcasts incoming feed items on its own, automatically. Just return an error
* if the webserver should not be rebroadcasting: e.g. if an invalid purchase is made.
*
* This function is passed in a userId, which it uses to fill in the FeedItem, if
* necessary. It then returns a new, filled-in feeditem.
*/
func HandleFeedItem(fi *FeedItem, userId string) (*FeedItem, error) {
if !bson.IsObjectIdHex(fi.GroupID) || !bson.IsObjectIdHex(userId) {
return nil, errors.New(invalidBsonIdHexErrorMessage)
}
switch fi.Type {
case FeedItemTypeComment:
comment := &Comment{}
err := json.Unmarshal(fi.Content, comment)
if err != nil {
return nil, err
}
comment.UserID = userId
return InsertAsFeedItem(FeedItemContent(comment), fi.GroupID)
case FeedItemTypeNotification:
notification := &Notification{}
err := json.Unmarshal(fi.Content, notification)
if err != nil {
return nil, err
}
return InsertAsFeedItem(FeedItemContent(notification), fi.GroupID)
case FeedItemTypePayment:
payment := &Payment{}
err := json.Unmarshal(fi.Content, payment)
if err != nil {
return nil, err
}
payment.UserId = userId
group, err := FindGroup(bson.ObjectIdHex(fi.GroupID))
if err != nil {
return nil, err
}
err = PayMember(group, payment.PayerID, payment.PayeeID, payment.AmountInCents)
if err != nil {
return nil, err
}
return InsertAsFeedItem(FeedItemContent(payment), fi.GroupID)
case FeedItemTypePurchase:
purchase := &Purchase{}
err := json.Unmarshal(fi.Content, purchase)
if err != nil {
return nil, err
}
purchase.UserId = userId
group, err := FindGroup(bson.ObjectIdHex(fi.GroupID))
if err != nil {
return nil, err
}
err = DoPurchase(group, purchase.PayerID,
purchase.AmountInCents, purchase.Expected)
if err != nil {
return nil, err
}
return InsertAsFeedItem(FeedItemContent(purchase), fi.GroupID)
default:
return nil, errors.New(fmt.Sprint("invalid FeedItem type: ", fi.Type))
}
}
示例8: checkType
// This function check if the real type behind the interface value is the one wished by the validators
func checkType(validator *Validator, valueToTest interface{}, errors *[]*DataError) bool {
kind := reflect.ValueOf(valueToTest).Kind()
switch kind {
case reflect.Slice:
array := validator.Type[0:2] // indeed, the type representation string begins with []
_type := validator.Type[2:] // here we have the type after []
if array != "[]" {
*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: reflect.TypeOf(valueToTest).String()})
return false
} else {
for _, value := range valueToTest.([]interface{}) {
vtype := reflect.TypeOf(value).String()
if vtype != _type {
// _type can be bson.ObjectId... which is basicly a string. So the condition above may fail but the type is in fact correct. Let's check:
if stringValue, ok := value.(string); ok && _type == "bson.ObjectId" && bson.IsObjectIdHex(stringValue) {
return true
} else {
*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: "[] contains " + reflect.TypeOf(value).String()})
return false
}
}
}
}
case reflect.Map:
// json maps are map[string]interface{}, but we could test for more...
parts := strings.SplitAfter(validator.Type, "]")
for key, value := range valueToTest.(map[string]interface{}) {
vtype := reflect.TypeOf(value)
// such as is the string key a correct ObjectId ?
if parts[0] == "map[bson.ObjectId]" {
if !bson.IsObjectIdHex(key) {
*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: "one of the indexes at least is not valid ObjectId: " + key})
return false
}
}
// or test the real value behind interface{}
if vtype.String() != parts[1] {
*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: "one of the map values is of type: " + vtype.String()})
return false
}
}
default:
if _type := reflect.TypeOf(valueToTest); _type != nil && _type.String() != validator.Type {
// bson.ObjectId is match as a string, let's try to save them off the error pireflect.TypeOf(valueToTest)reflect.TypeOf(valueToTest)t
if _type.String() == "string" && bson.IsObjectIdHex(valueToTest.(string)) && validator.Type == "bson.ObjectId" {
return true
} else {
// ok, let'em fall
*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: _type.String()})
return false
}
}
}
return true
}
示例9: queryTokenWithCredential
// Find token with credential
func (d *DefaultMongoStore) queryTokenWithCredential(table string, clientID string, userID string) Token {
/* Condition validation */
if len(clientID) == 0 || len(userID) == 0 || !bson.IsObjectIdHex(clientID) || !bson.IsObjectIdHex(userID) {
return nil
}
token := new(DefaultToken)
if err := mongo.EntityWithCriteria(table, bson.M{"user_id": bson.ObjectIdHex(userID), "client_id": bson.ObjectIdHex(clientID)}, token); err != nil {
return nil
}
return token
}
示例10: DeleteAddress
func DeleteAddress(w http.ResponseWriter, req *http.Request, params martini.Params, enc encoding.Encoder, shop *cart.Shop) string {
var c cart.Customer
customerId := params["id"]
if !bson.IsObjectIdHex(customerId) {
apierror.GenerateError("invalid customer reference", nil, w, req)
return ""
}
c.Id = bson.ObjectIdHex(customerId)
c.ShopId = shop.Id
if err := c.Get(); err != nil {
apierror.GenerateError("", err, w, req)
return ""
}
addressId := params["address"]
if !bson.IsObjectIdHex(addressId) {
apierror.GenerateError("invalid address reference", nil, w, req)
return ""
}
// Make sure this isn't the default address
if c.DefaultAddress != nil && c.DefaultAddress.Id.Hex() == addressId {
apierror.GenerateError("removing a default address is not allowed", nil, w, req)
return ""
}
found := false
for i, addr := range c.Addresses {
if addr.Id.Hex() == addressId {
c.Addresses = append(c.Addresses[:i], c.Addresses[i+1:]...)
found = true
break
}
}
if !found {
apierror.GenerateError("invalid address reference", nil, w, req)
return ""
}
if err := c.Update(); err != nil {
apierror.GenerateError(err.Error(), err, w, req)
return ""
}
return ""
}
示例11: RemoveAnswer
// RemoveAnswer adds an answer to a form gallery. Duplicated answers
// are de-duplicated automatically and will not return an error.
func RemoveAnswer(context interface{}, db *db.DB, id, submissionID, answerID string) (*Gallery, error) {
log.Dev(context, "RemoveAnswer", "Started : Gallery[%s]", id)
if !bson.IsObjectIdHex(id) {
log.Error(context, "RemoveAnswer", ErrInvalidID, "Completed")
return nil, ErrInvalidID
}
if !bson.IsObjectIdHex(submissionID) {
log.Error(context, "RemoveAnswer", ErrInvalidID, "Completed")
return nil, ErrInvalidID
}
objectID := bson.ObjectIdHex(id)
answer := Answer{
SubmissionID: bson.ObjectIdHex(submissionID),
AnswerID: answerID,
}
if err := answer.Validate(); err != nil {
log.Error(context, "RemoveAnswer", err, "Completed")
return nil, err
}
f := func(c *mgo.Collection) error {
u := bson.M{
"$pull": bson.M{
"answers": answer,
},
}
log.Dev(context, "RemoveAnswer", "MGO : db.%s.update(%s, %s)", c.Name, mongo.Query(objectID), mongo.Query(u))
return c.UpdateId(objectID, u)
}
if err := db.ExecuteMGO(context, Collection, f); err != nil {
log.Error(context, "RemoveAnswer", err, "Completed")
return nil, err
}
gallery, err := Retrieve(context, db, id)
if err != nil {
log.Error(context, "RemoveAnswer", err, "Completed")
return nil, err
}
log.Dev(context, "RemoveAnswer", "Completed")
return gallery, nil
}
示例12: GetUser
func (uc UserController) GetUser(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
// Grab id
id := p.ByName("location_id")
// Verify id is ObjectId, otherwise bail
if !bson.IsObjectIdHex(id) {
rw.WriteHeader(404)
return
}
// Grab id
oid := bson.ObjectIdHex(id)
// Stub user
u := UserLocation{}
// Fetch user
if err := uc.session.DB("mongodatabase").C("CMPE273").FindId(oid).One(&u); err != nil {
rw.WriteHeader(404)
return
}
// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)
// Write content-type, statuscode, payload
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)
fmt.Fprintf(rw, "%s", uj)
}
示例13: Delete
func (c *InterfaceController) Delete(w http.ResponseWriter, r *http.Request) {
// Get ID
id := mux.Vars(r)["id"]
// Validate ObjectId
if !bson.IsObjectIdHex(id) {
w.WriteHeader(http.StatusNotFound)
return
}
// Get object id
oid := bson.ObjectIdHex(id)
// Initialize empty struct
s := models.Interface{}
// Get entry
if err := c.session.DB(c.database).C("interfaces").FindId(oid).One(&s); err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
// Remove entry
if err := c.session.DB(c.database).C("interfaces").RemoveId(oid); err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
// Write status
jsonWriter(w, r, s, http.StatusOK, c.envelope)
}
示例14: showPackageHandler
// URL: /p/{packageId}
// 显示第三方包详情
func showPackageHandler(handler *Handler) {
vars := mux.Vars(handler.Request)
packageId := vars["packageId"]
if !bson.IsObjectIdHex(packageId) {
http.NotFound(handler.ResponseWriter, handler.Request)
return
}
c := handler.DB.C(CONTENTS)
package_ := Package{}
err := c.Find(bson.M{"_id": bson.ObjectIdHex(packageId), "content.type": TypePackage}).One(&package_)
if err != nil {
message(handler, "没找到该包", "请检查链接是否正确", "error")
fmt.Println("showPackageHandler:", err.Error())
return
}
var categories []PackageCategory
c = handler.DB.C(PACKAGE_CATEGORIES)
c.Find(nil).All(&categories)
handler.renderTemplate("package/show.html", BASE, map[string]interface{}{
"package": package_,
"categories": categories,
"active": "package",
})
}
示例15: UpdateLocations
func (uc UserController) UpdateLocations(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
id := p.ByName("id")
if !bson.IsObjectIdHex(id) {
w.WriteHeader(404)
return
}
oid := bson.ObjectIdHex(id)
l := structure.Location{}
json.NewDecoder(r.Body).Decode(&l)
str := getURL(l.Address, l.City, l.State)
getLocation(&l, str)
l.Id = oid
if err := uc.session.DB("cmpe273_project").C("hello").Update(bson.M{"_id": l.Id}, bson.M{"$set": bson.M{"address": l.Address, "city": l.City, "state": l.State, "zip": l.Zip, "coordinate.lat": l.Coordinate.Lat, "coordinate.lng": l.Coordinate.Lng}}); err != nil {
w.WriteHeader(404)
return
}
if err := uc.session.DB("cmpe273_project").C("hello").FindId(oid).One(&l); err != nil {
w.WriteHeader(404)
return
}
lj, _ := json.Marshal(l)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
fmt.Fprintf(w, "%s", lj)
}