Skip to content

Instantly share code, notes, and snippets.

@nidhi-canopas
Created July 20, 2022 07:44
Show Gist options
  • Select an option

  • Save nidhi-canopas/183f282af66be3d8194b0a191bf2f0a3 to your computer and use it in GitHub Desktop.

Select an option

Save nidhi-canopas/183f282af66be3d8194b0a191bf2f0a3 to your computer and use it in GitHub Desktop.
package controllers
import (
"errors"
"gorm-test/database"
"gorm-test/models"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type UserRepo struct {
Db *gorm.DB
}
func New() *UserRepo {
db := database.InitDb()
db.AutoMigrate(&models.User{})
return &UserRepo{Db: db}
}
//create user
func (repository *UserRepo) CreateUser(c *gin.Context) {
var user models.User
c.BindJSON(&user)
err := models.CreateUser(repository.Db, &user)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, user)
}
//get users
func (repository *UserRepo) GetUsers(c *gin.Context) {
var user []models.User
err := models.GetUsers(repository.Db, &user)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, user)
}
//get user by id
func (repository *UserRepo) GetUser(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var user models.User
err := models.GetUser(repository.Db, &user, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithStatus(http.StatusNotFound)
return
}
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, user)
}
// update user
func (repository *UserRepo) UpdateUser(c *gin.Context) {
var user models.User
id, _ := strconv.Atoi(c.Param("id"))
err := models.GetUser(repository.Db, &user, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithStatus(http.StatusNotFound)
return
}
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.BindJSON(&user)
err = models.UpdateUser(repository.Db, &user)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, user)
}
// delete user
func (repository *UserRepo) DeleteUser(c *gin.Context) {
var user models.User
id, _ := strconv.Atoi(c.Param("id"))
err := models.DeleteUser(repository.Db, &user, id)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, gin.H{"message": "User deleted successfully"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment