show first entry

This commit is contained in:
u80864958
2025-04-10 16:17:58 +02:00
commit fb2d784421
46 changed files with 15997 additions and 0 deletions

View File

@ -0,0 +1,39 @@
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)
}

11
backend/blog/resource.go Normal file
View File

@ -0,0 +1,11 @@
package blog
import "gorm.io/gorm"
type Service struct {
db *gorm.DB
}
func New(db *gorm.DB) *Service {
return &Service{db: db}
}