package server import ( "log" "strings" "time" "git.nefrace.ru/nefrace/nashboard/storage" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) type newBookmarkForm struct { Name string Url string FolderID primitive.ObjectID Tags []string } func (s Server) handleNewBookmark(c Context) error { var form newBookmarkForm err := DecodeJSON(c.R.Body, &form) if err != nil { return ApiError{Err: "can't decode json to bookmark: " + err.Error(), Status: 400} } ctx := c.R.Context() user := ctx.Value(CtxValue("user")).(*storage.User) bookmark := storage.Bookmark{ Id: primitive.NewObjectID(), Name: form.Name, Url: form.Url, FolderID: form.FolderID, Tags: form.Tags, UserID: user.Id, Created: time.Now(), } _, err = s.Db.CreateBookmark(&bookmark) if err != nil { return ApiError{Err: "can't safe bookmark: " + err.Error(), Status: 500} } return c.WriteJSON(201, &bookmark) } func (s Server) handleGetBookmarks(c Context) error { ctx := c.R.Context() user := ctx.Value(CtxValue("user")).(*storage.User) // Getting currently logged in user query := c.R.URL.Query() filter := bson.D{{Key: "userid", Value: user.Id}} // Filter only bookmarks owned by User for k, v := range query { var f bson.E q := strings.Split(k, "_") if len(q) == 1 { // If param is like "name" or "url" we're using exact matching f = bson.E{Key: k, Value: v[0]} } else { if q[1] == "like" { // If it's like "name_like", we're using regex f = bson.E{Key: q[0], Value: bson.D{{Key: "$regex", Value: v[0]}}} } } filter = append(filter, f) // Applying query filters to user filter } bookmarks, err := s.Db.GetBookmarks(&filter) if err != nil { log.Println("Error getting bookmarks: ", err) c.WriteJSON(200, []*storage.Bookmark{}) } return c.WriteJSON(200, bookmarks) }