update and delete

This commit is contained in:
u80864958
2025-04-28 14:25:58 +02:00
parent cc92a11060
commit f027ee7e39
10 changed files with 149 additions and 8 deletions

Binary file not shown.

View File

@ -4,11 +4,13 @@ import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
"github.com/gorilla/mux"
)
func (s Service) CreatePost(w http.ResponseWriter, r *http.Request) {
func (s Service) SavePost(w http.ResponseWriter, r *http.Request) {
var post model.Post
if err := json.NewDecoder(r.Body).Decode(&post); err != nil {
w.WriteHeader(http.StatusBadRequest)
@ -37,3 +39,23 @@ func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&posts)
w.WriteHeader(http.StatusOK)
}
func (s Service) DeletePost(w http.ResponseWriter, r *http.Request) {
idStr, ok := mux.Vars(r)["postID"]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
err = s.db.Delete(&model.Post{}, id).Error
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
}
w.WriteHeader(http.StatusNoContent)
}

View File

@ -30,7 +30,9 @@ func main() {
r := mux.NewRouter()
r.Use(cors.HandlerForOrigin("*"))
r.Handle("/login", auth.Login(user, password, []byte(secret))).Methods("POST")
r.Handle("/posts", auth.Authenticated([]byte(secret))(blg.CreatePost)).Methods("POST")
r.Handle("/posts", auth.Authenticated([]byte(secret))(blg.SavePost)).Methods("POST")
r.Handle("/posts", auth.Authenticated([]byte(secret))(blg.SavePost)).Methods("PUT")
r.Handle("/posts/{postID}", auth.Authenticated([]byte(secret))(blg.DeletePost)).Methods("DELETE")
r.Handle("/posts", http.HandlerFunc(blg.GetAllPosts)).Methods("GET")
r.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The CORS middleware should set up the headers for you