func SearchPage(user common.User, session sessions.Session, r render.Render, req *http.Request) { src, err := handleSearch(req.URL.Query()) if err != nil { r.Error(400) } status := common.GetCodeSourceStatus(src) id := rand.Int63() params := req.URL.Query() usr := params.Get("user") repo := params.Get("repo") session.Set(id, usr+"/"+repo) data := struct { common.User Pagename string Theme string SourceStatus string WS_ID int64 Source *common.CodeSource }{user, "search", "standard", string(status), id, src} r.HTML(200, "search", data) }
func (this *Schedules) Add(req *http.Request, authUser models.AuthUser, render render.Render) { var schedule models.Schedule if decode(req, render, &schedule) != nil { return } schedule.Id = 0 schedule.UserId = authUser.Id errors := models.NewErrors() if err := schedule.Validate(this.db, errors); err != nil { render.Error(500) return } if errors.Count() > 0 { render.JSON(400, errors) return } if this.db.Save(&schedule).Error != nil { render.Error(500) return } }
func CreateAdmin(r render.Render, req *http.Request) { if len(cache.Users) > 0 { r.Error(404) return } if req.Method == "GET" { r.HTML(200, "user_add", map[string]interface{}{}) return } req.ParseForm() values := req.Form m := &model.User{} m.Account = values.Get("account") m.Password = model.Md5(values.Get("password")) m.Info = values.Get("info") m.Name = values.Get("name") if !checkNull([]string{m.Account, m.Password, m.Info, m.Name}...) { service.Logs.Error("args err") return } m.Status = model.UserStatusAdmin _, err := dao.AddUser(m) if err != nil { service.Logs.Error("dao.InsertUser err(%v)", err) return } r.Redirect("/", 302) return }
func updateList(db *bolt.DB, params martini.Params, req *http.Request, r render.Render) { var l DistributionList body, _ := ioutil.ReadAll(req.Body) req.Body.Close() err := json.Unmarshal(body, &l) if err != nil { r.Error(http.StatusBadRequest) return } if params["id"] != l.Id { r.Error(http.StatusBadRequest) return } // marshal back out to json to normalize our data j, err := json.Marshal(l) db.Update( func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucketDistributionLists)) return b.Put([]byte(l.Id), j) }) r.Status(http.StatusOK) }
func allLists(db *bolt.DB, params martini.Params, req *http.Request, r render.Render) { var lists []DistributionList err := db.View( func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucketDistributionLists)) return b.ForEach(func(k, v []byte) error { var d DistributionList err := json.Unmarshal(v, &d) // TODO(dgryski): skip invalid keys instead of aborting on corrupt db?[ if err != nil { return err } lists = append(lists, d) return nil }) }) if err != nil { r.Error(http.StatusInternalServerError) return } r.JSON(http.StatusOK, lists) }
func GetPaste(params martini.Params, ren render.Render, r *http.Request, cf *swift.Connection, mc *memcache.Client) { cachedPaste, err := mc.Get(params["pasteid"]) format := params["format"] if err != nil { log.Println(err) } var paste Paste paste.PasteId = params["pasteid"] if cachedPaste == nil { log.Println("Asking swift for ", params["pasteid"]) cfPaste, err := cf.ObjectGetBytes("go-cfpaste", params["pasteid"]) if err != nil { if err.Error() == "Object Not Found" { ren.HTML(404, "404", paste) return } else { log.Println(err) ren.Error(500) return } } err = json.Unmarshal(cfPaste, &paste) PanicIf(err) } else { log.Println("Cache hit for ", params["pasteid"]) err = json.Unmarshal(cachedPaste.Value, &paste) PanicIf(err) } if format == "json" { ren.JSON(200, paste) } else { ren.HTML(200, "paste", paste) } return }
func (h BuildersHandler) ServeHTTP(r render.Render) { if builders, err := GetBuilders(h.c); err == nil { r.JSON(200, builders) } else { r.Error(500) } }
// Delete a post // DELETE /post/1 func HandleDelete(post Post, r render.Render) { err := post.delete() if err != nil { r.Error(500) return } r.Status(200) }
// Update a post // PUT /post/1 func HandlePut(post Post, r render.Render) { err := post.update() if err != nil { r.Error(500) return } r.Status(200) }
// GET /users func GetUsers(r render.Render) { users := []db.User{} if db.DB.Find(&users).RecordNotFound() { r.Error(404) } else { r.HTML(200, "users", users) } }
// GET /users/user/:uuid/edit func GetUsersEdit(r render.Render, params martini.Params) { user := db.User{} if db.DB.Where("uuid = ?", params["uuid"]).First(&user).RecordNotFound() { r.Error(404) } else { r.HTML(200, "users/edit", user) } }
func List(r render.Render, params martini.Params, db *mgo.Database) { var available []models.AvailableTopic err := db.C(availableCollection).Find(nil).Sort("-updated_on").All(&available) if err != nil { r.Error(400) } r.HTML(200, "available/list", available) }
func Retrieve(c martini.Context, params martini.Params, r render.Render) { id, _ := strconv.Atoi(params["id"]) post, err := retrieve(id) if err != nil { r.Error(404) return } c.Map(post) }
func MediaHead(db gorm.DB, r render.Render, params martini.Params) { media := models.Media{} id, _ := strconv.Atoi(params["id"]) if err := db.First(&media, id).Error; err != nil { r.Error(http.StatusNotFound) return } r.Redirect(media.Url) }
// POST /validate func PostValidate(r render.Render, req *http.Request) { s := req.PostFormValue("session") session := db.Session{} if db.DB.Where("uuid = ?", s).First(&session).RecordNotFound() { r.Error(404) } else { r.Status(200) } }
// POST /authenticate func PostAuthenticate(r render.Render, req *http.Request) { email := req.PostFormValue("email") password := req.PostFormValue("password") session_id, err := db.Auth(email, password) if err != nil { r.Error(401) } else { r.JSON(200, map[string]interface{}{"session": session_id}) } }
func MediaPlay(db gorm.DB, r render.Render, params martini.Params) { media := models.Media{} id, _ := strconv.Atoi(params["id"]) if err := db.First(&media, id).Error; err != nil { r.Error(http.StatusNotFound) return } db.Model(&media).Update(&models.Media{Played: media.Played + 1}) r.Redirect(media.Url) }
// GET /users/:uuid/activate func GetUsersActivate(r render.Render, params martini.Params) { user := db.User{} if db.DB.Where("activation_token = ?", params["uuid"]).First(&user).RecordNotFound() { r.Error(404) } else { if err := user.Activate(); err != nil { r.Error(500) } r.Status(200) } }
// POST /auth func PostAuth(s sessions.Session, r render.Render, req *http.Request) { email := req.PostFormValue("email") password := req.PostFormValue("password") session_id, err := db.Auth(email, password) if err != nil { r.Error(401) } else { s.Set("user_session", session_id) r.Redirect("/") } }
// GET /users/user/:uuid/reset func GetUsersReset(r render.Render, params martini.Params) { user := db.User{} if db.DB.Where("uuid = ?", params["uuid"]).First(&user).RecordNotFound() { r.Error(404) } else { password := utils.RandPassword(8) user.Password = utils.Hash([]byte(password), []byte(user.Salt)) db.DB.Save(&user) go utils.SendResetPassword(user.Email, password) r.Redirect("/users") } }
// GET /users/user/:uuid/remove func GetUsersRemove(r render.Render, params martini.Params) { user := db.User{} if db.DB.Where("uuid = ?", params["uuid"]).First(&user).RecordNotFound() { r.Error(404) } else { if err := db.DB.Delete(&user).Error; err != nil { r.Error(500) } else { r.Redirect("/users") } } }
func findHero(db HeroDB, parms martini.Params, r render.Render) { u := (db).(*heroDB) id, _ := strconv.Atoi(parms["id"]) hero, ok := u.heros[id] if !ok { r.Error(http.StatusNotFound) return } r.JSON(http.StatusOK, hero) }
func doRanking(params martini.Params, r render.Render) { lang := params["language"] rankings, err := readGitHubStarRanking(lang) if err != nil { r.Error(400) } // render r.HTML(200, "ranking", ResponseRanking{ Language: lang, Rankings: rankings, }) }
func doSnapshot(logger *log.Logger, params martini.Params, r render.Render) { lang := params["language"] // levelDBへ保存 level, err := leveldb.Open("snapshot", &db.Options{}) if err != nil { r.Error(400) } defer level.Close() key := createSnapshotKey(lang, time.Now()) logger.Println("key: ", key) if _, err := level.Get([]byte(key), &db.ReadOptions{}); err != nil { res, err := http.Get(fmt.Sprintf(gitHubStarURL, lang)) if err != nil { r.Error(400) } data, err := ioutil.ReadAll(res.Body) if err != nil { r.Error(400) } if err := level.Set([]byte(key), data, &db.WriteOptions{}); err != nil { r.Error(400) } } r.JSON(200, nil) }
func removeList(db *bolt.DB, params martini.Params, req *http.Request, r render.Render) { id := params["id"] err := db.Update( func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucketDistributionLists)) return b.Delete([]byte(id)) }) if err != nil { r.Error(http.StatusInternalServerError) return } r.Status(http.StatusOK) }
/* Check Authorization token */ func AuthenticationMiddleware(req *http.Request, context martini.Context, r render.Render) { token := req.Header.Get("Authorization") if token == "" { r.Error(401) } uid, err := getUserUidFromToken(token) if err != nil { r.Error(401) } else { context.Map(*uid) context.Next() } }
func EnsureAuth(session sessions.Session, r render.Render, req *http.Request, c martini.Context) { id, ok := session.Get("id").(int64) if !ok || id == 0 { session.AddFlash("warning: You must login first!") session.Set("previous_url", req.RequestURI) r.Redirect("/signin") } else if ok { var user models.User err := utils.ORM.First(&user, id).Error if err != nil { r.Error(500) return } c.Map(user) } }
func getTaskInfo(params martini.Params, user User, r render.Render) { id := params["id"] if len(id) == 0 { r.Error(http.StatusBadRequest) return } task, err := GetTaskByTaskId(id) if err != nil { log.Debug(err) r.Error(http.StatusInternalServerError) return } r.JSON(200, task) }
func updateHero(db HeroDB, req *http.Request, r render.Render) { u := (db).(*heroDB) breq := new(BatmanRequest) body, _ := ioutil.ReadAll(req.Body) req.Body.Close() err := json.Unmarshal(body, &breq) hero := breq.Hero if err != nil { r.Error(http.StatusInternalServerError) return } u.heros[hero.Id] = hero r.JSON(http.StatusOK, hero) }
func (this *Syncs) Create(req *http.Request, authUser models.AuthUser, render render.Render) { syncs := []models.Sync{} if decode(req, render, &syncs) != nil { return } tx := this.db.Begin() userIds := utils.Set{} for _, sync := range syncs { sync.UserId = authUser.Id if q := tx.Save(&sync); q.Error != nil { tx.Rollback() render.Error(500) return } for _, syncUser := range sync.SyncUsers { syncUser.SyncId = sync.Id if syncUser.UserId != authUser.Id { userIds.Insert(syncUser.UserId) } if q := tx.Save(&syncUser); q.Error != nil { tx.Rollback() render.Error(500) return } } } if q := tx.Commit(); q.Error != nil { tx.Rollback() render.Error(500) return } go this.sendPushNotifications(userIds.ToSlice()) if authUser.FetchSyncs(this.db) != nil { render.Error(500) return } render.JSON(http.StatusOK, map[string]interface{}{"results": authUser.Syncs}) }