Sobes.tech
Junior — Middle

Can you explain the role of a controller in the clean architecture structure?

sobes.tech AI

Answer from AI

In clean architecture, the controller acts as an intermediary between the outside world (e.g., HTTP requests) and the internal layers of the application.

Main functions of the controller:

  • Receives incoming requests.
  • Extracts necessary data from the request.
  • Calls the appropriate use cases or interactors.
  • Forms a response for the client.

The controller does not contain business logic; it merely directs data and commands to the appropriate parts of the system.

Example in Go (simplified):

func UserController(w http.ResponseWriter, r *http.Request) {
    userID := r.URL.Query().Get("id")
    user, err := userUseCase.GetUserByID(userID)
    if err != nil {
        http.Error(w, "User not found", http.StatusNotFound)
        return
    }
    json.NewEncoder(w).Encode(user)
}

Here, the controller receives the request, calls the business logic, and returns the result to the client.