help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
go-rest-api
/
internal
/
handlers
RSK World
go-rest-api
Go REST API - Enterprise-grade REST API with JWT Authentication + PostgreSQL + Redis Caching + Docker + Comprehensive Testing + Educational Design
handlers
  • api_handler.go1.4 KB
  • auth_handler.go4.4 KB
  • auth_handler_test.go4.6 KB
  • category_handler.go5.2 KB
  • product_handler.go8.8 KB
  • upload_handler.go5 KB
category_handler.go
internal/handlers/category_handler.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package handlers

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/rskworld/go-rest-api/internal/database"
	"github.com/rskworld/go-rest-api/internal/models"
	"github.com/rskworld/go-rest-api/internal/response"
	"github.com/rskworld/go-rest-api/internal/validation"
)

type CategoryHandler struct{}

func NewCategoryHandler() *CategoryHandler {
	return &CategoryHandler{}
}

// CreateCategory godoc
// @Summary Create a new category
// @Description Create a new category with the input payload
// @Tags categories
// @Accept  json
// @Produce  json
// @Param category body models.Category true "Create category"
// @Success 201 {object} response.Response
// @Failure 400 {object} response.Response
// @Failure 500 {object} response.Response
// @Security BearerAuth
// @Router /categories [post]
func (h *CategoryHandler) CreateCategory(c *gin.Context) {
	var category models.Category
	if err := c.ShouldBindJSON(&category); err != nil {
		response.ValidationError(c, err.Error())
		return
	}

	// Validate the category data
	if err := validation.ValidateStruct(category); err != nil {
		response.ValidationError(c, err.Error())
		return
	}

	if result := database.DB.Create(&category); result.Error != nil {
		response.InternalServerError(c, "Failed to create category")
		return
	}

	response.Success(c, http.StatusCreated, "Category created successfully", category)
}

// GetCategories godoc
// @Summary Get list of categories
// @Description Get list of categories with pagination
// @Tags categories
// @Accept  json
// @Produce  json
// @Param page query int false "Page number"
// @Param limit query int false "Number of items per page"
// @Success 200 {object} response.Response
// @Failure 500 {object} response.Response
// @Router /categories [get]
func (h *CategoryHandler) GetCategories(c *gin.Context) {
	var categories []models.Category
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	offset := (page - 1) * limit

	if result := database.DB.Limit(limit).Offset(offset).Find(&categories); result.Error != nil {
		response.InternalServerError(c, "Failed to fetch categories")
		return
	}

	response.Success(c, http.StatusOK, "Categories retrieved successfully", gin.H{
		"data":  categories,
		"page":  page,
		"limit": limit,
	})
}

// GetCategory godoc
// @Summary Get a category by ID
// @Description Get details of a specific category by ID
// @Tags categories
// @Accept  json
// @Produce  json
// @Param id path int true "Category ID"
// @Success 200 {object} response.Response
// @Failure 404 {object} response.Response
// @Router /categories/{id} [get]
func (h *CategoryHandler) GetCategory(c *gin.Context) {
	id := c.Param("id")
	var category models.Category

	if result := database.DB.Preload("Products").First(&category, id); result.Error != nil {
		response.NotFound(c, "Category")
		return
	}

	response.Success(c, http.StatusOK, "Category retrieved successfully", category)
}

// UpdateCategory godoc
// @Summary Update a category
// @Description Update a category by ID
// @Tags categories
// @Accept  json
// @Produce  json
// @Param id path int true "Category ID"
// @Param category body models.Category true "Update category"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Failure 404 {object} response.Response
// @Security BearerAuth
// @Router /categories/{id} [put]
func (h *CategoryHandler) UpdateCategory(c *gin.Context) {
	id := c.Param("id")
	var category models.Category

	if result := database.DB.First(&category, id); result.Error != nil {
		response.NotFound(c, "Category")
		return
	}

	var updateData models.Category
	if err := c.ShouldBindJSON(&updateData); err != nil {
		response.ValidationError(c, err.Error())
		return
	}

	// Validate the update data
	if err := validation.ValidateStruct(updateData); err != nil {
		response.ValidationError(c, err.Error())
		return
	}

	// Update only non-zero fields
	if err := database.DB.Model(&category).Updates(updateData).Error; err != nil {
		response.InternalServerError(c, "Failed to update category")
		return
	}

	// Reload the updated category
	if err := database.DB.First(&category, id).Error; err != nil {
		response.InternalServerError(c, "Failed to retrieve updated category")
		return
	}

	response.Success(c, http.StatusOK, "Category updated successfully", category)
}

// DeleteCategory godoc
// @Summary Delete a category
// @Description Delete a category by ID
// @Tags categories
// @Accept  json
// @Produce  json
// @Param id path int true "Category ID"
// @Success 200 {object} response.Response
// @Failure 500 {object} response.Response
// @Security BearerAuth
// @Router /categories/{id} [delete]
func (h *CategoryHandler) DeleteCategory(c *gin.Context) {
	id := c.Param("id")
	if result := database.DB.Delete(&models.Category{}, id); result.Error != nil {
		response.InternalServerError(c, "Failed to delete category")
		return
	}

	response.Success(c, http.StatusOK, "Category deleted successfully", nil)
}
179 lines•5.2 KB
go

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer