|
| 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 | + err := models.GetAllUsers(&user) |
| 15 | + if err != nil { |
| 16 | + c.AbortWithStatus(http.StatusNotFound) |
| 17 | + } else { |
| 18 | + c.JSON(http.StatusOK, user) |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +//CreateUser ... Create User |
| 23 | +func CreateUser(c *gin.Context) { |
| 24 | + var user models.User |
| 25 | + c.BindJSON(&user) |
| 26 | + err := models.CreateUser(&user) |
| 27 | + if err != nil { |
| 28 | + fmt.Println(err.Error()) |
| 29 | + c.AbortWithStatus(http.StatusNotFound) |
| 30 | + } else { |
| 31 | + c.JSON(http.StatusOK, user) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +//GetUserByID ... Get the user by id |
| 36 | +func GetUserByID(c *gin.Context) { |
| 37 | + id := c.Params.ByName("id") |
| 38 | + var user models.User |
| 39 | + err := models.GetUserByID(&user, id) |
| 40 | + if err != nil { |
| 41 | + c.AbortWithStatus(http.StatusNotFound) |
| 42 | + } else { |
| 43 | + c.JSON(http.StatusOK, user) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +//UpdateUser ... Update the user information |
| 48 | +func UpdateUser(c *gin.Context) { |
| 49 | + var user models.User |
| 50 | + id := c.Params.ByName("id") |
| 51 | + err := models.GetUserByID(&user, id) |
| 52 | + if err != nil { |
| 53 | + c.JSON(http.StatusNotFound, user) |
| 54 | + } |
| 55 | + c.BindJSON(&user) |
| 56 | + err = models.UpdateUser(&user, id) |
| 57 | + if err != nil { |
| 58 | + c.AbortWithStatus(http.StatusNotFound) |
| 59 | + } else { |
| 60 | + c.JSON(http.StatusOK, user) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +//DeleteUser ... Delete the user |
| 65 | +func DeleteUser(c *gin.Context) { |
| 66 | + var user models.User |
| 67 | + id := c.Params.ByName("id") |
| 68 | + err := models.DeleteUser(&user, id) |
| 69 | + if err != nil { |
| 70 | + c.AbortWithStatus(http.StatusNotFound) |
| 71 | + } else { |
| 72 | + c.JSON(http.StatusOK, gin.H{"id" + id: "is deleted"}) |
| 73 | + } |
| 74 | +} |
0 commit comments