Golang项目目录结构的最佳实践

Golang项目目录结构的最佳实践 大家好,

假设我有一个足球API,并试图构建一个目录结构以使项目更有条理。当我们看下面的两种结构时,哪一种更符合Go的风格?我来自PHP(Symfony)背景,V2是那种方式,但我感觉V1才是Go的理想选择。我这样认为对吗?

谢谢

V1

.
|_ cmd
  |_ main.go
|_ internal
  |_ app
    |_ football.go
    |_ config.co
    |_ middleware.go
    |_ router.go
    |_ server.go
  |_ team
    |_ controller.go
    |_ entity.go
    |_ repository.go
    |_ service.go
  |_ league
    |_ controller.go
    |_ entity.go
    |_ repository.go
    |_ service.go

V2

.
|_ cmd
  |_ main.go
|_ internal
  |_ app
    |_ football.go
  |_ controller
    |_ league.go
    |_ team.go
  |_ config
    |_ config.co
  |_ middleware
    |_ middleware.go
  |_ entity
    |_ league.go
    |_ team.go
  |_ http
    |_ router.go
    |_ server.go
  |_ repository
    |_ league.go
    |_ team.go
  |_ service
    |_ league.go
    |_ team.go

更多关于Golang项目目录结构的最佳实践的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

我认为,真正需要的是组织你的代码,使其易于理解和易于修复或更新。

对我来说,V1 是正确的方式,因为我总是尝试按功能、按业务逻辑来组织我的代码。这样,根据业务需求,可以很容易地用特定的实现方式替换其中的某个部分,或者你甚至可以在另一个应用程序中重用这些单元(例如,如果你有一个足球应用程序和一个棒球应用程序,你可以重用 team 文件夹)。

这只是我的一点浅见…

更多关于Golang项目目录结构的最佳实践的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go项目中,V1的按领域(team、league)组织的方式更符合Go的风格。Go鼓励按功能/领域组织代码,而不是按技术角色(controller、service等)分层。V1的结构使得每个领域模块内聚性更高,更易于维护和测试。

示例代码结构可以这样组织:

// internal/team/team.go
package team

type Team struct {
    ID   string
    Name string
}

type Repository interface {
    FindByID(id string) (*Team, error)
}

type Service struct {
    repo Repository
}

func NewService(repo Repository) *Service {
    return &Service{repo: repo}
}

// internal/team/http.go
package team

import "net/http"

type Handler struct {
    service *Service
}

func (h *Handler) GetTeam(w http.ResponseWriter, r *http.Request) {
    // HTTP处理逻辑
}

这种组织方式的好处是:

  1. 领域相关的代码集中在一起
  2. 减少包之间的循环依赖
  3. 更容易进行单元测试
  4. 符合Go的"一个目录一个包"的哲学

对于共享的组件(如配置、中间件),可以放在internal/app或单独的internal/pkg目录中。路由注册可以在internal/app中统一处理。

回到顶部