package routes import ( "backend/database" "encoding/json" "github.com/go-chi/chi/v5" "net/http" "strconv" ) func RegisterNewsRoutes(r chi.Router) { r.Route("/", func(s chi.Router) { s.Get("/", getNews) s.Post("/", addPost) }) r.Route("/{id:[0-9]+}", func(s chi.Router) { s.Get("/", getPost) s.Put("/", updatePost) s.Delete("/", deletePost) }) } func getNews(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() offset, _ := strconv.Atoi(q.Get("offset")) limit, _ := strconv.Atoi(q.Get("limit")) if limit == 0 { limit = 20 } total, err := database.FetchTotalNews() if err != nil { Error(w, err) return } pagination := map[string]interface{}{ "offset": offset, "limit": limit, "total": total, } news, err := database.FetchNews(offset, limit) ResponsePagination(w, err, news, pagination) } func addPost(w http.ResponseWriter, r *http.Request) { body, err := ReadBody(r) if err != nil { Error(w, err) return } post := new(database.Post) err = json.Unmarshal(body, post) if err != nil { Error(w, err) return } uid, err := GetCurrentUserID(r) if err != nil { Error(w, err) return } post.AuthorID = uid createdPost, err := database.CreatePost(post) Response(w, err, createdPost) } func getPost(w http.ResponseWriter, r *http.Request) { id := IURLParam(r, "id") post, err := database.FetchPost(id) Response(w, err, post) } func updatePost(w http.ResponseWriter, r *http.Request) { id := IURLParam(r, "id") body, err := ReadBody(r) if err != nil { Error(w, err) return } post, err := database.FetchPost(id) if err != nil { Error(w, err) return } err = json.Unmarshal(body, post) if err != nil { Error(w, err) return } err = database.UpdatePost(post) if err != nil { Error(w, err) return } w.WriteHeader(http.StatusNoContent) } func deletePost(w http.ResponseWriter, r *http.Request) { id := IURLParam(r, "id") err := database.DeletePost(id) if err != nil { Error(w, err) return } w.WriteHeader(http.StatusNoContent) }