func HandleIndex(r render.Render) { tip := models.Tips{} db := GetDBInstance() total, err := db.C("tips").Count() if err != nil || total == 0 { r.HTML(200, "500", nil) return } index := getRandomIndex(total) if index == total { index = total - 1 } db.C("tips").Find(nil).Skip(index).One(&tip) if db.Session != nil { defer db.Session.Close() } r.HTML(200, "index", map[string]interface{}{ "Comment": tip.Comment, "Content": tip.Content, "Id": tip.Id.Hex(), "IsIndex": true}) }
func popularLinks(r render.Render) { links, err := store.Popular() if err != nil { log.WithField("package", "web").Error(err) r.JSON(500, map[string]string{ "error": err.Error(), }) return } var formattedLinks []map[string]interface{} for _, link := range links { formattedLinks = append(formattedLinks, map[string]interface{}{ "id": link.ID(), "title": link.Title, "url": link.URL, "score": link.Score, }) } r.JSON(200, formattedLinks) }
func HandleCreateIRLMoji(r render.Render, bindErr binding.Errors, im models.IRLMoji, db *models.DB, backchannel Backchannel) { if bindErr.Count() > 0 { r.JSON(400, JsonErrBinding(bindErr)) return } if backchannel.UserId() == "" { r.JSON(403, JsonErr("The provided credentials were invalid.")) return } user, err := db.GetUserWithId(backchannel.UserId()) if err != nil { r.JSON(403, "Could not find a user with your credentials.") return } // Now let's create that user, shall we? insertedIM, err := db.InsertIM(user.Id, im.Emoji, im.Picture) if err != nil { log.Println("Error creating user:"******"Sorry, an internal server error has occurred.")) return } r.JSON(200, map[string]*models.IRLMoji{"irlmoji": insertedIM}) }
func ArticlesIndex(r render.Render) { hal := HAL{} hal.Links = map[string]Link{ "self": Link{"/articles", false}, "show": Link{"/articles/{id}", true}, } //result := []Todo{} // //rows, err := rethink.Table("todos").Run(session) //if err != nil { // log.Println(err) //} // //for rows.Next() { // var t Todo // err := rows.Scan(&t) // if err != nil { // log.Println(err) // } // result = append(result, t) //} //r.JSON(200, result) //r.JSON(200, "hello") r.JSON(200, hal) }
// Called on a POST to /events/:id/comments // Assuming valid comment; Adds the comment under the given id func AddComment(db *mgo.Database, r render.Render, comment models.Comment, p martini.Params) { var eventId bson.ObjectId // Create a unique id comment.Id = bson.NewObjectId() if bson.IsObjectIdHex(p["event_id"]) { eventId = bson.ObjectIdHex(p["event_id"]) } else { r.JSON(400, "Bad Request: Invalid Event ID") return } comment.EventId = eventId // TODO Should be the user Id comment.CreatedBy = bson.NewObjectId() comment.CreatedAt = time.Now().UTC() err := db.C("comments").Insert(comment) if err != nil { panic(err) } r.JSON(201, comment) }
func HandleRandomJsonTip(r render.Render) { db := GetDBInstance() tip := models.Tips{} api := models.API{} total, _ := db.C("tips").Count() index := getRandomIndex(total) db.C("tips").Find(nil).Skip(index).One(&tip) err := db.C("apis").Find(bson.M{"type": "json"}).One(&api) api.Count++ if err != nil { db.C("apis").Insert(&models.API{Id: bson.NewObjectId(), Type: "json", Count: 0}) } else { db.C("apis").Update(bson.M{"type": "json"}, bson.M{"type": "json", "count": api.Count}) } data, err := json.Marshal(api) if err == nil { sendAll(data) } if db.Session != nil { defer db.Session.Close() } r.JSON(200, tip) }
func SearchAnswersNew(r render.Render, db *mgo.Database, req *http.Request, session sessions.Session) { lastGameIdSearched := session.Get("last_game_id_searched") templateData := map[string]interface{}{"metatitle": "Battle Answers", "currentPath": req.URL.Path, "lastGameIdSearched": lastGameIdSearched, "games": models.GetGameRecs(db, nil)} r.HTML(200, "search_answers/new", templateData) }
func handleTemplate(r render.Render, req *http.Request, t Template, s ServerList) { tmpl_data := make(map[string]interface{}) tmpl_data["title"] = t.Title tmpl_data["server"] = getServerInfo(req, s) r.HTML(200, t.Tmpl, tmpl_data) }
func EventListHandler(r render.Render) { search := bson.M{"data.start_time": bson.M{"$gte": time.Now()}} sort := "data.start_time" var results []Event err := db.Find(&Event{}, search).Sort(sort).All(&results) if err != nil && err != mgo.ErrNotFound { panic(err) } if err == mgo.ErrNotFound { fmt.Println("No such object in db. Redirect") //http.Redirect(w, r, "/404/", http.StatusFound) return } type templateData struct { Context *conf.Context Events []Event } data := templateData{conf.DefaultContext(conf.Config), results} r.HTML(200, "event_list", data) }
func getDrop(params martini.Params, db *database.Database, r render.Render) { d, err := db.GetDrop(params["url"]) if err != nil { r.JSON(500, map[string]interface{}{"error": err.Error()}) } else { r.JSON(200, map[string]interface{}{"drop": d}) } }
func GetPost(params martini.Params, r render.Render) { hd := services.GetDb() var results []models.Posts hd.Where("id", "=", params["id"]).Limit(1).Find(&results) r.JSON(200, results) }
func ProjectGet(db gorm.DB, r render.Render, params martini.Params) { var project models.Project if err := db.First(&project, params["id"]).Error; err != nil { r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Project not found"}) return } r.JSON(http.StatusOK, project) }
func ListPosts(params martini.Params, r render.Render) { hd := services.GetDb() var results []models.Posts hd.Find(&results) r.JSON(200, results) }
func removeHero(db HeroDB, parms martini.Params, r render.Render) { u := (db).(*heroDB) id, _ := strconv.Atoi(parms["id"]) delete(u.heros, id) r.JSON(http.StatusOK, nil) }
func validateSession(r render.Render, s sessions.Session) { isLogin := s.Get("IsLogin") if isLogin == nil { fmt.Println("Not login...") r.Redirect("/admin/login") } }
func allHeros(db HeroDB, parms martini.Params, r render.Render) { u := (db).(*heroDB) var heros []Hero for _, v := range u.heros { heros = append(heros, v) } r.JSON(http.StatusOK, heros) }
func renderTutorial(ren render.Render) { var tutorial Tutorial file, err := ioutil.ReadFile("neutrino.json") if err != nil { panic(err) } json.Unmarshal(file, &tutorial) ren.JSON(200, tutorial) }
///////////////////////////////////////////////////////////////////////////////////////////// // Controller Actions ///////////////////////////////////////////////////////////////////////////////////////////// func GamesIndex(r render.Render, db *mgo.Database, req *http.Request) { var recs []models.GameRec recs = models.GetGameRecs(db, nil) templateData := map[string]interface{}{"metatitle": "Battle Answers", "currentPath": req.URL.Path, "recs": populateGameDisplays(db, recs)} r.HTML(200, "games/index", templateData) }
func deleteDrop(params martini.Params, db *database.Database, r render.Render) { url := params["url"] err := db.DeleteDrop(url) if err != nil { r.JSON(500, map[string]interface{}{"error": err.Error()}) } else { r.JSON(200, map[string]interface{}{"ok": url}) } }
///////////////////////////////////////////////////////////////////////////////////////////// // Controller Actions ///////////////////////////////////////////////////////////////////////////////////////////// func BattleAnswersIndex(r render.Render, db *mgo.Database, req *http.Request) { var recs []models.BattleAnswerRec recs = models.GetBattleAnswerRecs(db, nil) templateData := map[string]interface{}{"metatitle": "Battle Answers", "currentPath": req.URL.Path, "recs": helpers.GetBattleAnswerDisplays(db, recs)} r.HTML(200, "battle_answers/index", templateData) }
func AdminAddTips(req *http.Request, r render.Render, db *mgo.Database) { content := req.FormValue("tip") comment := req.FormValue("comment") tip := models.Tips{Id: bson.NewObjectId(), Content: content, Comment: comment} db.C("tips").Insert(tip) r.Redirect("/admin/tips") }
func listDrops(db *database.Database, r render.Render) { // when there's none it returns a null? drops, err := json.Marshal(db.ListDrops()) fmt.Println(drops) if err != nil { r.JSON(500, map[string]interface{}{"error": err}) } else { r.JSON(200, map[string]interface{}{"drops": string(drops)}) } }
func NotFoundHandler(r render.Render) { type templateData struct { Context *conf.Context } data := templateData{conf.DefaultContext(conf.Config)} r.HTML(200, "404", data) }
func HomeHandler(r render.Render) { type templateData struct { Context *conf.Context } data := templateData{conf.DefaultContext(conf.Config)} r.HTML(200, "home", data) }
func EventGrabHandler(r render.Render) { type templateData struct { Context *conf.Context } data := templateData{conf.DefaultContext(conf.Config)} r.HTML(200, "event_grab", data) }
func AdminModifyCasts(r render.Render, db *mgo.Database, params martini.Params) { cast := models.Casts{} db.C("casts").FindId(bson.ObjectIdHex(params["Id"])).One(&cast) r.HTML(200, "admin/casts_modify", map[string]interface{}{ "IsCasts": true, "Id": params["Id"], "Cast": cast}, render.HTMLOptions{Layout: "admin/layout"}) }
// Render error page func renderError(code int, r render.Render) { r.HTML(404, "404", Page{ HttpCode: 404, HttpMethod: "GET", Template: "404", Path: "/404", Slug: "404", Title: "Página não encontrada - Hera Modas", Description: "A página que você tentou acessar não existe ou foi removida.", }) }
func HomeIndex(r render.Render) { hal := HAL{} hal.Links = map[string]Link{ "self": Link{"/", false}, "portfolio": Link{"/portfolio", false}, } r.JSON(200, hal) }
func ShowLoginPage(r render.Render, s sessions.Session) { isLogin := s.Get("IsLogin") if isLogin != nil { r.Redirect("/admin/index") return } r.HTML(200, "admin/login", map[string]interface{}{ "IsAbout": true}, render.HTMLOptions{}) }
func Login(r *http.Request, render render.Render, db *gorp.DbMap, s sessions.Session) { user := User{} email, password := r.FormValue("email"), r.FormValue("password") err := db.SelectOne(&user, "Select * from users where email=? ", email) //tmp_pass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) //err := db.QueryRow("select id, password from users where email=$1", email).Scan(&userId, &dbPasswd) if err != nil || bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) != nil { render.HTML(400, "404", "") } s.Set("userId", user.Id) render.HTML(200, "dashboard", "") }