|
| 1 | +package controllers |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "github.com/gin-gonic/gin" |
| 8 | + "github.com/golang-mitrah/gin-RestAPI-postgres-orm/models" |
| 9 | +) |
| 10 | + |
| 11 | +// GetUsers ... Get all users |
| 12 | +func GetUsers(c *gin.Context) { |
| 13 | + var user []models.User |
| 14 | + |
| 15 | + err := models.GetAllUsers(&user) |
| 16 | + if err != nil { |
| 17 | + c.AbortWithStatus(http.StatusNotFound) |
| 18 | + } else { |
| 19 | + c.JSON(http.StatusOK, user) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +// CreateUser ... Create User |
| 24 | +func CreateUser(c *gin.Context) { |
| 25 | + var user models.User |
| 26 | + |
| 27 | + if err := c.BindJSON(&user); err != nil { |
| 28 | + fmt.Println("failed to bind the json", err.Error()) |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + err := models.CreateUser(&user) |
| 33 | + if err != nil { |
| 34 | + fmt.Println(err.Error()) |
| 35 | + c.AbortWithStatus(http.StatusNotFound) |
| 36 | + } else { |
| 37 | + c.JSON(http.StatusOK, user) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// GetUserByID ... Get the user by id |
| 42 | +func GetUserByID(c *gin.Context) { |
| 43 | + var user models.User |
| 44 | + |
| 45 | + id := c.Params.ByName("id") |
| 46 | + |
| 47 | + err := models.GetUserByID(&user, id) |
| 48 | + if err != nil { |
| 49 | + c.AbortWithStatus(http.StatusNotFound) |
| 50 | + } else { |
| 51 | + c.JSON(http.StatusOK, user) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// UpdateUser ... Update the user information |
| 56 | +func UpdateUser(c *gin.Context) { |
| 57 | + var user models.User |
| 58 | + |
| 59 | + id := c.Params.ByName("id") |
| 60 | + |
| 61 | + err := models.GetUserByID(&user, id) |
| 62 | + if err != nil { |
| 63 | + c.JSON(http.StatusNotFound, user) |
| 64 | + } |
| 65 | + |
| 66 | + if err := c.BindJSON(&user); err != nil { |
| 67 | + fmt.Println("failed to bind the json", err.Error()) |
| 68 | + return |
| 69 | + } |
| 70 | + |
| 71 | + err = models.UpdateUser(&user, id) |
| 72 | + if err != nil { |
| 73 | + c.AbortWithStatus(http.StatusNotFound) |
| 74 | + } else { |
| 75 | + c.JSON(http.StatusOK, user) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +// DeleteUser ... Delete the user |
| 80 | +func DeleteUser(c *gin.Context) { |
| 81 | + var user models.User |
| 82 | + |
| 83 | + id := c.Params.ByName("id") |
| 84 | + |
| 85 | + err := models.DeleteUser(&user, id) |
| 86 | + if err != nil { |
| 87 | + c.AbortWithStatus(http.StatusNotFound) |
| 88 | + } else { |
| 89 | + c.JSON(http.StatusOK, gin.H{"id" + id: "is deleted"}) |
| 90 | + } |
| 91 | +} |
0 commit comments