11package controllers
22
33import (
4+ "context"
45 "fmt"
56 "github.com/gin-gonic/gin"
7+ "github.com/laironacosta/ms-gin-go/controllers/dto"
8+ "github.com/laironacosta/ms-gin-go/services"
69 "net/http"
710)
811
9- type User struct {
10- Name string `json:"name" binding:"required"`
11- Email string `json:"email" binding:"required,email"`
12+ type UserControllerInterface interface {
13+ Create (c * gin.Context )
14+ GetByEmail (c * gin.Context )
15+ UpdateByEmail (c * gin.Context )
16+ DeleteByEmail (c * gin.Context )
1217}
1318
14- func Create (c * gin.Context ) {
15- u := User {}
19+ type UserController struct {
20+ userService services.UserServiceInterface
21+ }
22+
23+ func NewUserController (userService services.UserServiceInterface ) UserControllerInterface {
24+ return & UserController {
25+ userService ,
26+ }
27+ }
28+
29+ func (ctr * UserController ) Create (c * gin.Context ) {
30+ u := dto.User {}
1631 if err := c .ShouldBindJSON (& u ); err != nil {
1732 c .JSON (http .StatusBadRequest , gin.H {
1833 "error" : err .Error (),
1934 })
2035 return
2136 }
2237
38+ if err := ctr .userService .Create (context .Background (), u ); err != nil {
39+ c .JSON (http .StatusBadRequest , gin.H {
40+ "error" : err .Error (),
41+ })
42+ return
43+ }
44+
2345 fmt .Printf ("Request received: %+v \n " , u )
2446 c .JSON (http .StatusOK , gin.H {"message" : "created" })
2547}
2648
27- func GetByEmail (c * gin.Context ) {
49+ func ( ctr * UserController ) GetByEmail (c * gin.Context ) {
2850 e := c .Param ("email" )
2951
3052 fmt .Printf ("Path param received: %+v \n " , e )
31- c .JSON (http .StatusOK , User {
53+ c .JSON (http .StatusOK , dto. User {
3254 Email : e ,
3355 })
3456}
3557
36- func UpdateByEmail (c * gin.Context ) {
37- u := User {}
58+ func ( ctr * UserController ) UpdateByEmail (c * gin.Context ) {
59+ u := dto. User {}
3860 if err := c .ShouldBindJSON (& u ); err != nil {
3961 c .JSON (http .StatusBadRequest , gin.H {
4062 "error" : err .Error (),
@@ -49,7 +71,7 @@ func UpdateByEmail(c *gin.Context) {
4971 c .JSON (http .StatusOK , u )
5072}
5173
52- func DeleteByEmail (c * gin.Context ) {
74+ func ( ctr * UserController ) DeleteByEmail (c * gin.Context ) {
5375 e := c .Param ("email" )
5476
5577 fmt .Printf ("Path param received: %+v \n " , e )
0 commit comments