Files
old-ibcetvorke/cethttp/editor_handlers.go
2023-09-16 16:59:16 +02:00

67 lines
1.7 KiB
Go

package cethttp
import (
"database/sql"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/senaduka/cetvorke/database"
)
// editHandler handles the editing of an existing post.
func editHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
postID, err := strconv.Atoi(vars["postID"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Fetch the post from the database.
post, err := database.GetPost(postID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Check if the request method is POST.
if r.Method == "POST" {
// Get the edited content from the form.
editedContent := r.FormValue("editor")
editedTitle := r.FormValue("title")
// Update the post content.
post.GemtextContent = sql.NullString{String: editedContent, Valid: true}
post.Title = editedTitle
// Save the edited post to the database.
err := database.UpdatePost(post)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Redirect to the edited post.
http.Redirect(w, r, "/p/"+vars["postID"]+"/"+post.TitleSlug, http.StatusSeeOther)
return
}
// Display the edit form.
response := editorHtml5Page(post)
w.Write([]byte(response))
}
// newHandler handles the creation of a new post.
func newHandler(w http.ResponseWriter, r *http.Request) {
// Create a new empty post in the database.
newPost, err := database.CreateNewPost()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Redirect to the editHandler for the new post.
http.Redirect(w, r, "/editor/e/"+strconv.Itoa(newPost.ID), http.StatusSeeOther)
}