62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
package blog
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
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)
|
|
fmt.Fprint(w, err.Error())
|
|
return
|
|
}
|
|
|
|
if err := s.db.Save(&post).Error; err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
fmt.Fprint(w, err.Error())
|
|
}
|
|
|
|
json.NewEncoder(w).Encode(&post)
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
|
|
var posts []model.Post
|
|
|
|
if err := s.db.Preload("Comments").Order("created_at DESC").Find(&posts).Error; err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
fmt.Fprint(w, err.Error())
|
|
return
|
|
}
|
|
|
|
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)
|
|
}
|