go 服务端分层框架设计

框架分为四层。models,controllers,repositories,services
以User为例

1、controller示例

package controllers

import (
	"appserver/repositories"
	"appserver/services"
	"net/http"

	"github.com/gin-gonic/gin"
)

var UserControllerInstance *UserController

type UserController struct {
	userService services.UserService
}

func init() {
	userRepository := repositories.NewUserRepository()
	userService := services.NewUserService(userRepository)
	UserControllerInstance = NewUserController(userService)
}

func NewUserController(userService services.UserService) *UserController {
	return &UserController{
		userService: userService,
	}
}

func (uc *UserController) Login(c *gin.Context) {
	// 从请求中获取用户名和密码
	username := c.PostForm("username")
	password := c.PostForm("password")

	// 调用用户服务进行身份验证
	user, err := uc.userService.AuthenticateUser(username, password)
	if err != nil {
		// 处理身份验证失败的逻辑
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "Invalid credentials",
		})
		return
	}
	user.ID = 1
	// 身份验证成功,执行其他逻辑
	// ...

	// 返回响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Login successful",
	})
}

2、models示例

package models

import "time"

// User 表示用户模型
type User struct {
	ID        uint      `json:"id"`
	Username  string    `json:"username"`
	Password  string    `json:"-"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

// CreateUserInput 表示创建用户的输入数据
type CreateUserInput struct {
	Username string `json:"username"`
}

// UpdateUserInput 表示更新用户的输入数据
type UpdateUserInput struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

3、repositories示例

package repositories

import (
	"database/sql"
)

type UserRepository interface {
	IsValidUser(username, password string) bool
}

type userRepository struct {
	db *sql.DB
}

func NewUserRepository(db *sql.DB) UserRepository {
	return &userRepository{
		db: db,
	}
}

func (ur *userRepository) IsValidUser(username, password string) bool {
	stmt, err := ur.db.Prepare("SELECT COUNT(*) FROM users WHERE username = ? AND password = ?")
	if err != nil {
		// 处理错误
		return false
	}
	defer stmt.Close()

	var count int
	err = stmt.QueryRow(username, password).Scan(&count)
	if err != nil {
		// 处理查询错误
		return false
	}

	return count > 0
}

4、services示例

package services

import (
	"appserver/repositories"
)

type UserService interface {
	IsValidUser(username, password string) bool
}

type userService struct {
	userRepository repositories.UserRepository
}

func NewUserService(userRepository repositories.UserRepository) UserService {
	return &userService{
		userRepository: userRepository,
	}
}

func (us *userService) IsValidUser(username, password string) bool {
	return us.userRepository.IsValidUser(username, password)
}

5、请求消息处理

import(
"appserver/controllers"
)

// 用户登录
router.POST("/user/login", controllers.UserControllerInstance.Login)
posted @ 2023-07-14 11:23  zhaogaojian  阅读(69)  评论(0编辑  收藏  举报