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
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
- The
main
function in themain
package is the entry point for the application. - The
main
function calls theAPIRun
function from thecmd
package. - The
APIRun
function initializes the application's environment and establishes a connection to the database. - It creates an HTTP server using the
core.NewHTTPServer
function and passes the necessary context options, including the database and environment. - The
APIRun
function registers HTTP routes for handling requests related to the home and user modules using thehome.NewHomeHTTP
anduser.NewUserHTTP
functions, respectively. - The
NewUserHTTP
function in theuser
package sets up the HTTP routes for user-related operations and associates them with the corresponding handlers from theUserController
. - Each HTTP route in the
NewUserHTTP
function is associated with a specific handler method in theUserController
(e.g.,Pagination
,Find
,Create
,Update
,Delete
). - When a user sends an HTTP request to one of the registered routes, the corresponding handler method in the
UserController
is executed. - Each handler method in the
UserController
delegates the request to the user service for further processing. - The user service methods (
Create
,Update
,Find
,Pagination
,Delete
) interact with the repository to perform CRUD operations on the user data in the database. - The repository methods use the database connection to execute the necessary SQL queries and return the results to the user service.
- The user service methods process the data received from the repository and return the appropriate response to the handler methods in the
UserController
. - 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
Struct Definition: The
UserController
is defined as a struct that represents the controller for user-related operations.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.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.Service Interaction: Inside each handler method, an instance of the user service (
UserService
) is created usingservices.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.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.
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.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.