#CMSRE pattern

7 messages · Page 1 of 1 (latest)

radiant plume
#

is using controller-model-service-repository-entity a good thing for new project ?

#

controller

package controllers

import (
    "net/http"
    "encoding/json"
    "myapp/services"
)

func UserHandler(w http.ResponseWriter, r *http.Request) {
    // Parse request parameters
    userID := r.URL.Query().Get("userID")
    
    // Invoke service method
    user, err := services.GetUser(userID)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // Return response to client
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}
#

model

package models

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}
#

service

package services

import (
    "myapp/models"
    "myapp/repositories"
)

func GetUser(userID string) (*models.User, error) {
    // Invoke repository method to retrieve user
    userEntity, err := repositories.GetUser(userID)
    if err != nil {
        return nil, err
    }

    // Convert entity to model
    user := &models.User{
        ID:   userEntity.ID,
        Name: userEntity.Name,
    }

    return user, nil
}
#

repository

package repositories

import (
    "myapp/entities"
)

type UserRepository interface {
    GetUserByID(string) (*entities.User, error)
}

type MySQLUserRepository struct {
    // MySQL connection information
}

func (repo *MySQLUserRepository) GetUserByID(userID string) (*entities.User, error) {
    // Query MySQL database to retrieve user
    // ...
    // Construct entity from query result
    userEntity := &entities.User{
        ID:   userID,
        Name: "John Doe",
    }

    return userEntity, nil
}
#

entity

package entities

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}
#

whoaa whoaa whoaa, this example is messed up ><