今天分享一个在 GitHub 上有 3.5k stars 的 Go 项目:go-backend-clean-arch[1]。
该项目展示了一个 Golang 后端项目如何设计优雅的项目结构。
2.项目架构
3.Directory Explanation
.├── Dockerfile # Image file
├── api
│ ├── controller # Controllers
│ ├── middleware # Middleware (JWT authentication)
│ └── route # Route binding
├── bootstrap
│ ├── app.go # Core class
│ ├── database.go # Database
│ └── env.go # Configuration class
├── cmd
│ └── main.go # Startup command
├── docker-compose.yaml
├── domain # Domain layer
├── go.mod
├── go.sum
├── internal # Internal utilities
│ └── tokenutil
├── mongo # MongoDB
│ └── mongo.go
├── repository # Repository layer
└── usecase # Use case layer
3.1 参数配置和项目启动
./cmd/main.go
type Application struct {
Env *Env
Mongo mongo.Client
}
type Env struct {
AppEnv string `mapstructure:"APP_ENV"`
ServerAddress string `mapstructure:"SERVER_ADDRESS"`
ContextTimeout int `mapstructure:"CONTEXT_TIMEOUT"`
DBHost string `mapstructure:"DB_HOST"`
DBPort string `mapstructure:"DB_PORT"`
...
}
func main() {
// app is the instance of the entire application, managing key resources throughout its lifecycle
app := bootstrap.App()
// Configuration variables
env := app.Env
// Database instance
db := app.Mongo.Database(env.DBName)
defer app.CloseDBConnection()
timeout := time.Duration(env.ContextTimeout) * time.Second
// Creating a gin instance
gin := gin.Default()
// Route binding
route.Setup(env, timeout, db, gin)
// Running the server
gin.Run(env.ServerAddress)
}
下面将以登录逻辑为例,说明三层架构。
3.2 接口层
./api/controller/login_controller.go
LoginController 包含配置类和 LoginUsecase 接口(定义业务层的行为)。
// Business layer interface
type SignupUsecase interface {
Create(c context.Context, user *User) error
GetUserByEmail(c context.Context, email string) (User, error)
CreateAccessToken(user *User, secret string, expiry int) (accessToken string, err error)
CreateRefreshToken(user *User, secret string, expiry int) (refreshToken string, err error)
}
type LoginController struct {
LoginUsecase domain.LoginUsecase
Env *bootstrap.Env
}
func (lc *LoginController) Login(c *gin.Context) {
var request domain.LoginRequest
err := c.ShouldBind(&request)
if err != nil {
c.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()})
return
}
user, err := lc.LoginUsecase.GetUserByEmail(c, request.Email)
if err != nil {
c.JSON(http.StatusNotFound, domain.ErrorResponse{Message: "User not found with the given email"})
return
}
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password)) != nil {
c.JSON(http.StatusUnauthorized, domain.ErrorResponse{Message: "Invalid credentials"})
return
}
accessToken, err := lc.LoginUsecase.CreateAccessToken(&user, lc.Env.AccessTokenSecret, lc.Env.AccessTokenExpiryHour)
if err != nil {
c.JSON(http.StatusInternalServerError, domain.ErrorResponse{Message: err.Error()})
return
}
refreshToken, err := lc.LoginUsecase.CreateRefreshToken(&user, lc.Env.RefreshTokenSecret, lc.Env.RefreshTokenExpiryHour)
if err != nil {
c.JSON(http.StatusInternalServerError, domain.ErrorResponse{Message: err.Error()})
return
}
loginResponse := domain.LoginResponse{
AccessToken: accessToken,
RefreshToken: refreshToken,
}
c.JSON(http.StatusOK, loginResponse)
}
3.3 业务层
./usecase/login_usecase.go
loginUsecase 结构实现了 LoginUsecase 接口。
// Data anti-corruption layer interface
type UserRepository interface {
Create(c context.Context, user *User) error
Fetch(c context.Context) ([]User, error)
GetByEmail(c context.Context, email string) (User, error)
GetByID(c context.Context, id string) (User, error)
}
type loginUsecase struct {
userRepository domain.UserRepository
contextTimeout time.Duration
}
func NewLoginUsecase(userRepository domain.UserRepository, timeout time.Duration) domain.LoginUsecase {
return &loginUsecase{
userRepository: userRepository,
contextTimeout: timeout,
}
}
func (lu *loginUsecase) GetUserByEmail(c context.Context, email string) (domain.User, error) {
ctx, cancel := context.WithTimeout(c, lu.contextTimeout)
defer cancel()
return lu.userRepository.GetByEmail(ctx, email)
}
func (lu *loginUsecase) CreateAccessToken(user *domain.User, secret string, expiry int) (accessToken string, err error) {
return tokenutil.CreateAccessToken(user, secret, expiry)
}
func (lu *loginUsecase) CreateRefreshToken(user *domain.User, secret string, expiry int) (refreshToken string, err error) {
return tokenutil.CreateRefreshToken(user, secret, expiry)
}
3.4 Anti-Corruption 层
./repository/user_repository.go userRepository 结构实现了 UserRepository 接口。它内部持有 mongo.Database 接口(该接口定义了数据层的行为)和集合实例的名称。
// Data operation layer interface
type Database interface {
Collection(string) Collection
Client() Client
}
type userRepository struct {
database mongo.Database
collection string
}
func NewUserRepository(db mongo.Database, collection string) domain.UserRepository {
return &userRepository{
database: db,
collection: collection,
}
}
func (ur *userRepository) Create(c context.Context, user *domain.User) error {
collection := ur.database.Collection(ur.collection)
_, err := collection.InsertOne(c, user)
return err
}
func (ur *userRepository) Fetch(c context.Context) ([]domain.User, error) {
collection := ur.database.Collection(ur.collection)
opts := options.Find().SetProjection(bson.D{{Key: "password", Value: 0}})
cursor, err := collection.Find(c, bson.D{}, opts)
if err != nil {
return nil, err
}
var users []domain.User
err = cursor.All(c, &users)
if users == nil {
return []domain.User{}, err
}
return users, err
}
func (ur *userRepository) GetByEmail(c context.Context, email string) (domain.User, error) {
collection := ur.database.Collection(ur.collection)
var user domain.User
err := collection.FindOne(c, bson.M{"email": email}).Decode(&user)
return user, err
}
func (ur *userRepository) GetByID(c context.Context, id string) (domain.User, error) {
collection := ur.database.Collection(ur.collection)
var user domain.User
idHex, err := primitive.ObjectIDFromHex(id)
if err != nil {
return user, err
}
err = collection.FindOne(c, bson.M{"_id": idHex}).Decode(&user)
return user, err
}
3.5 数据层
./mongo/mongo.go
实现 mongo.Database 接口。通过 mongoDatabase 结构的两个方法,你可以获得相应的 Client 实例和 Collection 实例来操作数据库。
type mongoDatabase struct {
db *mongo.Database
}
func (md *mongoDatabase) Collection(colName string) Collection {
collection := md.db.Collection(colName)
return &mongoCollection{coll: collection}
}
func (md *mongoDatabase) Client() Client {
client := md.db.Client()
return &mongoClient{cl: client}
}
4. 单例和封装
检查 ./cmd/main.go 中的路由绑定逻辑:route.Setup(env, timeout, db, gin)。
func Setup(env *bootstrap.Env, timeout time.Duration, db mongo.Database, gin *gin.Engine) {
publicRouter := gin.Group("")
// All Public APIs
NewSignupRouter(env, timeout, db, publicRouter)
NewLoginRouter(env, timeout, db, publicRouter)
NewRefreshTokenRouter(env, timeout, db, publicRouter)
protectedRouter := gin.Group("")
// Middleware to verify AccessToken
protectedRouter.Use(middleware.JwtAuthMiddleware(env.AccessTokenSecret))
// All Private APIs
NewProfileRouter(env, timeout, db, protectedRouter)
NewTaskRouter(env, timeout, db, protectedRouter)
}
进一步检查 NewLoginRouter 后发现,在注册由路由触发的控制器方法时,数据层中已经创建并共享了所需的数据库。
此外,业务层和控制器层的实例都是在服务启动前创建的,它们依次嵌套并保持不变。
因此,所有结构都是单子结构,类似于按顺序连接的树状结构。
func NewLoginRouter(env *bootstrap.Env, timeout time.Duration, db mongo.Database, group *gin.RouterGroup) {
ur := repository.NewUserRepository(db, domain.CollectionUser)
lc := &controller.LoginController{
LoginUsecase: usecase.NewLoginUsecase(ur, timeout),
Env: env,
}
group.POST("/login", lc.Login)
}
这种方法可以强制执行资源限制,防止开发人员跨模块调用实例, 这可能会导致循环依赖等问题和其他安全问题。
以上就是一个标准 Golang 后端的简洁架构,大家可以参考。
go-backend-clean-arch: https://github.com/amitshekhariitbhu/go-backend-clean-architecture