40 lines
897 B
Go
40 lines
897 B
Go
package blog
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
|
|
)
|
|
|
|
func (s Service) CreatePost(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)
|
|
}
|