package handler import ( "go-rest-api/model" "log" "net/http" "github.com/labstack/echo/v4" "go.mongodb.org/mongo-driver/bson" ) // AttachArticleHandlersToRouter func func AttachArticleHandlersToRouter(e *echo.Echo) { h := NewArticlesHandler() e.GET("/rabbit", h.testRabbit) g := e.Group("/articles") g.GET("", h.getAllArticles) g.GET("/:id", h.getOneArticle) g.POST("", h.createArticle) g.PUT("/:id", h.updateArticle) g.DELETE("/:id", h.removeArticle) } // NewArticlesHandler return new Articles Handler func NewArticlesHandler() ArticlesHandler { return ArticlesHandler{BaseHandler: *NewHandler()} } // ArticlesHandler type type ArticlesHandler struct { BaseHandler } // ArticleGenerateHeavyPDFMessage Struct that holds all data necessary for demo action type ArticleGenerateHeavyPDFMessage struct { Title string `json:"title"` Content string `json:"content"` Pages int `json:"pages"` } func (h *ArticlesHandler) testRabbit(c echo.Context) error { log.Println("test rabbit publish method calling...") q := h.amqp.DeclareQueue("article_queue_test") m := ArticleGenerateHeavyPDFMessage{ Title: "Test title", Content: "Lorem ipsum dolor sit amet", Pages: 10, } body, _ := h.JSONEncode(m) h.amqp.Publish(q.Name, body, "application/json") response := "Please wait until generating pdf or some other long task (in rabbitMQ queue) done" return c.JSON(http.StatusOK, response) } func (h *ArticlesHandler) getAllArticles(c echo.Context) error { coll := &model.Articles{} articles := h.BaseHandler.GetAllObjects(&model.Article{}, coll, bson.D{}) return c.JSON(http.StatusOK, articles) } func (h *ArticlesHandler) getOneArticle(c echo.Context) error { id := c.Param("id") art := &model.Article{} if _, err := h.BaseHandler.GetSingleObject(art, id); err != nil { return err } return c.JSON(http.StatusOK, art) } func (h *ArticlesHandler) createArticle(c echo.Context) error { art := &model.Article{} c.Bind(art) if _, err := h.BaseHandler.CreateObject(art); err != nil { return err } return c.JSON(http.StatusCreated, art) } func (h *ArticlesHandler) updateArticle(c echo.Context) error { id := c.Param("id") model := &model.Article{} art, err := h.BaseHandler.GetSingleObject(model, id) if err != nil { return err } DeserializeFromRequest(c.Request(), art) if _, err := h.BaseHandler.UpdateObject(art); err != nil { return err } return c.JSON(http.StatusOK, art) } func (h *ArticlesHandler) removeArticle(c echo.Context) error { id := c.Param("id") model := &model.Article{} art, err := h.BaseHandler.GetSingleObject(model, id) if err != nil { return err } if err := h.BaseHandler.RemoveObject(art); err != nil { return err } return c.NoContent(http.StatusOK) }