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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章