Gin 控制器如何只依赖 service 接口,避免直接引用 repo 实现?

解读

在国内一线/二线互联网公司的 Go 后端面试中,这道题常被用来考察候选人对“依赖倒置 + 接口隔离”原则的理解深度。
面试官真正想听的不是“把 repo 包 import 删掉”这么简单,而是:

  1. 你如何在不改变 Gin 路由注册方式的前提下,让 controller 层只感知 service 接口;
  2. 你如何落地“依赖注入”与“代码组织”,使得单测、接口文档、wire 自动生成都能跑通;
  3. 你是否清楚“接口放哪、实现放哪、注册放哪”这三件事在 Go 工程化里的最佳实践。

如果回答只是“用接口”,却讲不清“谁提供实现、谁负责注入、谁保证生命周期”,会被直接判定为“只背过八股”。

知识点

  1. 依赖倒置原则(DIP):高层模块(controller)不依赖低层模块(repo),二者都依赖抽象(service interface)。
  2. 接口所有权:接口由“使用者”——也就是 controller——拥有,定义在 internal/service 或 internal/ports,而不是由“实现者” repo 提供,避免循环依赖。
  3. 依赖注入(DI)手段:
    • 手动注入:main 函数里 NewHandler(svc service.UserService);
    • 构造函数注入:handler 结构体字段存接口,NewXxxHandler 返回 *XxxHandler;
    • 代码生成:Google wire、Uber fx,在国内大厂均落地,可自动生成 wire_gen.go。
  4. 生命周期管理:app 启动阶段一次性建好 repo → service → handler,避免在请求粒度的 c.Request.Context() 里再 new,防止内存泄漏。
  5. 单测写法:用 gomock 或 mockery 生成 service mock,注入到 handler,验证 http 状态码与业务错误码,repo 层单测完全跳过。
  6. 代码目录范例(符合《Go 项目布局》中文社区共识):
    internal/
    ├─ ports/ // 接口定义,controller 依赖这里
    ├─ service/ // 接口实现,依赖 repo 接口
    ├─ repo/ // 数据层实现
    ├─ server/ // http handler,只引用 ports
    └─ wire.go // 依赖注入描述文件

答案

下面给出“可落地、可单测、可 wire 生成”的最小完整范例,可直接搬进面试白板。

  1. 定义接口(由 controller 侧拥有)
// internal/ports/user_service.go
package ports

import "context"

type UserDTO struct {
    ID   int64  `json:"id"`
    Name string `json:"name"`
}

type UserService interface {
    GetByID(ctx context.Context, id int64) (*UserDTO, error)
}
  1. 控制器只依赖 ports
// internal/server/user_handler.go
package server

import (
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "gitlab.company.com/xxx/internal/ports"
)

type UserHandler struct {
    svc ports.UserService
}

func NewUserHandler(svc ports.UserService) *UserHandler {
    return &UserHandler{svc: svc}
}

func (h *UserHandler) GetByID(c *gin.Context) {
    id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
    dto, err := h.svc.GetByID(c.Request.Context(), id)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
        return
    }
    c.JSON(http.StatusOK, dto)
}
  1. service 实现依赖 repo 接口(同样由 service 拥有)
// internal/service/user_service.go
package service

import (
    "context"
    "gitlab.company.com/xxx/internal/ports"
    "gitlab.company.com/xxx/internal/repo"
)

type userService struct {
    repo repo.UserRepo // repo 接口,定义在 internal/repo/repo.go
}

func NewUserService(r repo.UserRepo) ports.UserService {
    return &userService{repo: r}
}

func (s *userService) GetByID(ctx context.Context, id int64) (*ports.UserDTO, error) {
    po, err := s.repo.Get(ctx, id)
    if err != nil {
        return nil, err
    }
    return &ports.UserDTO{ID: po.ID, Name: po.Name}, nil
}
  1. repo 实现
// internal/repo/user_repo.go
package repo

import (
    "context"
    "gorm.io/gorm"
)

type UserRepo interface {
    Get(ctx context.Context, id int64) (*UserPO, error)
}

type userRepo struct {
    db *gorm.DB
}

func NewUserRepo(db *gorm.DB) UserRepo {
    return &userRepo{db: db}
}

func (r *userRepo) Get(ctx context.Context, id int64) (*UserPO, error) {
    var po UserPO
    if err := r.db.WithContext(ctx).First(&po, id).Error; err != nil {
        return nil, err
    }
    return &po, nil
}

type UserPO struct {
    ID   int64  `gorm:"column:id;primaryKey"`
    Name string `gorm:"column:name"`
}
  1. main 函数(手动注入版,白板手写最快)
// cmd/main.go
package main

import (
    "github.com/gin-gonic/gin"
    "gitlab.company.com/xxx/internal/repo"
    "gitlab.company.com/xxx/internal/server"
    "gitlab.company.com/xxx/internal/service"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func main() {
    dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})

    // 依赖倒置链条:repo → service → handler
    userRepo := repo.NewUserRepo(db)
    userSvc := service.NewUserService(userRepo)
    userHdl := server.NewUserHandler(userSvc)

    r := gin.Default()
    r.GET("/users/:id", userHdl.GetByID)
    _ = r.Run(":8080")
}
  1. 单测示例(handler 层)
// internal/server/user_handler_test.go
func TestUserHandler_GetByID(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    mockSvc := mocks.NewMockUserService(ctrl)
    mockSvc.EXPECT().GetByID(gomock.Any(), int64(1)).Return(&ports.UserDTO{ID: 1, Name: "alice"}, nil)

    h := NewUserHandler(mockSvc)
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)
    c.Request = httptest.NewRequest("GET", "/users/1", nil)
    c.Params = gin.Params{{Key: "id", Value: "1"}}

    h.GetByID(c)
    assert.Equal(t, http.StatusOK, w.Code)
}

至此,controller 层 import 的只有 internal/ports,完全没有出现 internal/repo,完成“只依赖 service 接口”的硬性要求。

拓展思考

  1. 如果团队规模再大一层,如何把 service 再拆为 domain service 与 application service?
    domain service 放纯业务规则,不依赖 repo;application service 负责编排 repo 与 domain,controller 只依赖 application service 接口。
  2. 当链路出现消息队列、缓存、外部 RPC 时,接口如何分层?
    国内主流做法:按“北向”与“南向”再建一套 internal/adapter/ports,controller 只依赖北向,repo、cache、mq 都归为南向,实现细节对北向不可见。
  3. 在 Kubernetes 云原生场景下,如何利用 wire 的 ProviderSet 把数据库连接、配置中心、观测组件一次性注入?
    可在 internal/wire.go 里声明 var SuperSet = wire.NewSet(NewDB, NewConfig, NewUserRepo, NewUserService, NewUserHandler),然后 wire 命令生成 wire_gen.go,main 函数只剩 10 行,CI 自动校验生成文件是否过期,防止手动改错。