func homeHandler(w http.ResponseWriter, req *http.Request) { username := auth.GetUserName(req) text, err := ioutil.ReadFile("static/sitetext/home") checkErr(err, "Could not load static text") context := Context{ Title: "Scrambled Spirits Collective", Username: username, StaticText: template.HTML(text), } db.Order("created_at desc").Find(&context.Posts) // Fills context.Posts with posts from the database. err = render(w, context, "templates/main.html") checkErr(err, "Problem generating homepage") }
// TODO Restructure - subfunctions (error handling) func editHandler(w http.ResponseWriter, req *http.Request) { context := Context{Username: auth.GetUserName(req)} context.Posts = append(context.Posts, models.Post{}) if context.Username != "" { // If they have an authentication cookie post := &context.Posts[0] if len(req.URL.Path[len("/edit/"):]) > 0 { // If a post ID is referred to in the URL urlID, err := strconv.Atoi(req.URL.Path[len("/edit/"):]) //Get the target post ID from URL checkErr(err, "Could not get postID from URL") post.ID = uint(urlID) db.FirstOrCreate(post) // If db contains post.ID, copy the entry to post; else create an entry } switch req.Method { case "GET": err := render(w, context, "templates/edit.html") checkErr(err, "Could not render Edit template") case "POST": if len(req.FormValue("refreshButton")) > 0 { // Check whether they pressed the "update" button buildArtistMap() } else if len(req.FormValue("deleteButton")) > 0 { // Check whether they pressed the "delete" button db.Table("posts").Delete(post) for artistName, _ := range ArtistContextMap { db.Table("Tag"+artistName).Where("post_id = ?", post.ID).Delete(models.Tag{}) } } else if len(req.FormValue("saveButton")) > 0 { // Check whether they pressed the "save" button post.Title = req.FormValue("title") post.Author = req.FormValue("author") post.Body = req.FormValue("body") db.Save(&post) // TODO look into "bind" library for getting form values & converting to/from time.Time for key := range ArtistContextMap { err := checkTagCheckbox(key, post.ID, req) checkErr(err, "Problem parsing 'tag' checkboxes.") } } http.Redirect(w, req, "/", 302) } } else { // If no auth cookie http.NotFound(w, req) } }