1
0
go-rss-aggregator/handler_feed.go

61 lines
1.5 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"git.rpuzonas.com/rpuzonas/go-rss-aggregator/internal/database"
)
func (apiCfg *apiConfig) handlerCreateFeed(w http.ResponseWriter, r *http.Request, user User) {
type parameters struct {
Name string `json:"name"`
URL string `json:"url"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(&params)
if err != nil {
respondWithError(w, 400, fmt.Sprintf("Error parsing JSON: %v", err))
return
}
now := time.Now().UTC()
feed, err := apiCfg.DB.CreateFeed(r.Context(), database.CreateFeedParams{
UpdatedAt: now,
CreatedAt: now,
Name: params.Name,
Url: params.URL,
UserID: user.ID,
})
if err != nil {
respondWithError(w, 400, fmt.Sprintf("Couldn't create user: %v", err))
return
}
respondWithJSON(w, 200, databaseFeedToFeed(feed))
}
func (apiCfg *apiConfig) handlerGetCreatedFeeds(w http.ResponseWriter, r *http.Request, user User) {
feeds, err := apiCfg.DB.GetFeedsByUser(r.Context(), user.ID)
if err != nil {
respondWithError(w, 400, fmt.Sprintf("Couldn't list feeds: %v", err))
return
}
respondWithJSON(w, 200, databaseFeedsToFeeds(feeds))
}
func (apiCfg *apiConfig) handlerGetAllFeeds(w http.ResponseWriter, r *http.Request) {
feeds, err := apiCfg.DB.GetFeeds(r.Context())
if err != nil {
respondWithError(w, 400, fmt.Sprintf("Couldn't list feeds: %v", err))
return
}
respondWithJSON(w, 200, databaseFeedsToFeeds(feeds))
}