Skip to content
On this page

Controller

the controller component responsible for handling user-related operations within the application. It acts as an intermediary between the user interface (HTTP requests) and the underlying services and models.

Refers to the code from

modules/user/user.controller.go

Details
go
package user

import (
  "gitlab.finema.co/finema/golang-template/requests"
  "gitlab.finema.co/finema/golang-template/services"
  core "gitlab.finema.co/finema/idin-core"
  "gitlab.finema.co/finema/idin-core/utils"
  "net/http"
)

type UserController struct {
}

// Pagination handles the pagination request for users
func (m UserController) Pagination(c core.IHTTPContext) error {
  userSvc := services.NewUserService(c)
  res, ierr := userSvc.Pagination(c.GetPageOptions())
  if ierr != nil {
    return c.JSON(ierr.GetStatus(), ierr.JSON())
  }

  return c.JSON(http.StatusOK, res)
}

// Find retrieves a user by ID
func (m UserController) Find(c core.IHTTPContext) error {
  userSvc := services.NewUserService(c)
  user, err := userSvc.Find(c.Param("id"))
  if err != nil {
    return c.JSON(err.GetStatus(), err.JSON())
  }

  return c.JSON(http.StatusOK, user)
}

// Create creates a new user
func (m UserController) Create(c core.IHTTPContext) error {
  input := &requests.UserCreate{}
  if err := c.BindWithValidate(input); err != nil {
    return c.JSON(err.GetStatus(), err.JSON())
  }

  userSvc := services.NewUserService(c)
  payload := &services.UserCreatePayload{}
  _ = utils.Copy(payload, input)
  user, err := userSvc.Create(payload)
  if err != nil {
    return c.JSON(err.GetStatus(), err.JSON())
  }

  return c.JSON(http.StatusCreated, user)
}

// Update updates an existing user by ID
func (m UserController) Update(c core.IHTTPContext) error {
  input := &requests.UserUpdate{}
  if err := c.BindWithValidate(input); err != nil {
    return c.JSON(err.GetStatus(), err.JSON())
  }

  userSvc := services.NewUserService(c)
  payload := &services.UserUpdatePayload{}
  _ = utils.Copy(payload, input)
  user, err := userSvc.Update(c.Param("id"), payload)
  if err != nil {
    return c.JSON(err.GetStatus(), err.JSON())
  }

  return c.JSON(http.StatusCreated, user)
}

// Delete deletes a user by ID
func (m UserController) Delete(c core.IHTTPContext) error {
  userSvc := services.NewUserService(c)
  err := userSvc.Delete(c.Param("id"))
  if err != nil {
    return c.JSON(err.GetStatus(), err.JSON())
  }

  return c.NoContent(http.StatusNoContent)
}

Overview

  1. The main function in the main package is the entry point for the application.
  2. The main function calls the APIRun function from the cmd package.
  3. The APIRun function initializes the application's environment and establishes a connection to the database.
  4. It creates an HTTP server using the core.NewHTTPServer function and passes the necessary context options, including the database and environment.
  5. The APIRun function registers HTTP routes for handling requests related to the home and user modules using the home.NewHomeHTTP and user.NewUserHTTP functions, respectively.
  6. The NewUserHTTP function in the user package sets up the HTTP routes for user-related operations and associates them with the corresponding handlers from the UserController.
  7. Each HTTP route in the NewUserHTTP function is associated with a specific handler method in the UserController (e.g., Pagination, Find, Create, Update, Delete).
  8. When a user sends an HTTP request to one of the registered routes, the corresponding handler method in the UserController is executed.
  9. Each handler method in the UserController delegates the request to the user service for further processing.
  10. The user service methods (Create, Update, Find, Pagination, Delete) interact with the repository to perform CRUD operations on the user data in the database.
  11. The repository methods use the database connection to execute the necessary SQL queries and return the results to the user service.
  12. The user service methods process the data received from the repository and return the appropriate response to the handler methods in the UserController.
  13. The handler methods in the UserController format the response as JSON and send it back to the user as an HTTP response.

This is a high-level overview of the code flow in the provided codebase.In the provided code, the UserController implements the controller concept, which is a component of the Model-View-Controller (MVC) architectural pattern. The controller is responsible for handling incoming requests, coordinating the flow of data, and generating appropriate responses. Here's an explanation of the controller concept in the context of the UserController:

Code flow

  1. Struct Definition: The UserController is defined as a struct that represents the controller for user-related operations.

  2. Handler Methods: The UserController contains multiple handler methods, each corresponding to a different HTTP request for user operations such as pagination, finding a user, creating a user, updating a user, and deleting a user. These handler methods are responsible for processing incoming requests and generating appropriate responses.

  3. Request Context: Each handler method takes a core.IHTTPContext parameter, which represents the context of the incoming HTTP request. This context object provides access to request parameters, request body, response writer, and other information related to the request.

  4. Service Interaction: Inside each handler method, an instance of the user service (UserService) is created using services.NewUserService(c). The user service encapsulates the business logic for user operations and interacts with the underlying data storage (repository) to perform CRUD operations on user data.

  5. Error Handling: The handler methods handle potential errors that may occur during the execution of the user service methods. They check for errors returned by the user service methods and generate appropriate error responses if necessary. Error responses include the HTTP status code and error message, which are returned to the client as JSON.

  6. Data Transformation: In some handler methods (e.g., Create, Update), input data is parsed from the request body and transformed into service-specific payload objects ( e.g., UserCreatePayload, UserUpdatePayload). This helps decouple the controller layer from the service layer by using service-specific data structures.

  7. Response Generation: After successful processing of the request, the handler methods generate response data, either by obtaining data from the user service or by constructing appropriate response objects. The response data is then serialized into JSON format using the c.JSON() method and sent back to the client as an HTTP response.

Conclusion

By implementing the controller concept, the UserController serves as an intermediary between the HTTP requests and the underlying user service. It receives incoming requests, delegates business logic to the service layer, handles errors, and generates appropriate responses. This separation of concerns helps maintain clean code architecture and promotes modularity and testability.

Maintained by Passakon Puttasuwan & Dev Core Team.