diff --git a/internal/photos/api/check_body.go b/internal/photos/api/check_body.go new file mode 100644 index 0000000..039a58c --- /dev/null +++ b/internal/photos/api/check_body.go @@ -0,0 +1,14 @@ +package api + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +func (s *Service) RequireBody(c *gin.Context) { + if c.Request.Method == "POST" && c.Request.ContentLength == 0 { + s.Error(c, http.StatusBadRequest, ErrReqMissingBody) + return + } +} diff --git a/internal/photos/api/dump.go b/internal/photos/api/dump.go new file mode 100644 index 0000000..1e9fd79 --- /dev/null +++ b/internal/photos/api/dump.go @@ -0,0 +1,15 @@ +package api + +import ( + "bytes" + "encoding/json" +) + +func (s *Service) Dump(o interface{}) { + b := bytes.NewBuffer([]byte{}) + enc := json.NewEncoder(b) + enc.SetIndent("", " ") + enc.Encode(o) + + s.Logger.Printf("%s", b.Bytes()) +} diff --git a/internal/photos/api/helpers.go b/internal/photos/api/helpers.go deleted file mode 100644 index b74c8b8..0000000 --- a/internal/photos/api/helpers.go +++ /dev/null @@ -1,36 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "net/http" - - "github.com/gin-gonic/gin" -) - -func (s *Service) Recovery(c *gin.Context) { - defer func() { - if err := recover(); err != nil { - s.Logger.Println("[PANIC]", err) - c.JSON(http.StatusInternalServerError, gin.H{ - "error": "an unexpected error occur", - }) - } - }() - c.Next() -} - -func (s *Service) Dump(o interface{}) { - b := bytes.NewBuffer([]byte{}) - enc := json.NewEncoder(b) - enc.SetIndent("", " ") - enc.Encode(o) - - s.Logger.Printf("%s", b.Bytes()) -} - -func (s *Service) Error(c *gin.Context, code int, err error) { - c.AbortWithStatusJSON(code, gin.H{ - "error": err.Error(), - }) -} diff --git a/internal/photos/api/recovery.go b/internal/photos/api/recovery.go new file mode 100644 index 0000000..505abe4 --- /dev/null +++ b/internal/photos/api/recovery.go @@ -0,0 +1,17 @@ +package api + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +func (s *Service) Recovery(c *gin.Context) { + defer func() { + if err := recover(); err != nil { + s.Logger.Print("[PANIC]", err) + s.Error(c, http.StatusInternalServerError, ErrUnexpected) + } + }() + c.Next() +}