前言
依賴注入的好處和特點這里不講述了,本篇文章主要介紹gin框架如何實現依賴注入,將項目解耦。
項目結構
├── cmd 程序入口
├── common 通用模塊代碼
├── config 配置文件
├── controller API控制器
├── docs 數據庫文件
├── models 數據表實體
├── page 頁面數據返回實體
├── repository 數據訪問層
├── router 路由
├── service 業務邏輯層
├── vue-admin Vue前端頁面代碼
相信很多Java或者.NET的碼友對這個項目結構還是比較熟悉的,現在我們就用這個項目結構在gin框架中實現依賴注入。這里主要介紹controller、service和repository。
數據訪問層repository
- 首先定義IStartRepo接口,里面包括Speak方法
//IStartRepo 定義IStartRepo接口
type IStartRepo interface {
Speak(message string) string
}
- 實現該接口,這里就不訪問數據庫了,直接返回數據
//StartRepo 注入數據庫
type StartRepo struct {
Source datasource.IDb `inject:""`
}
//Speak 實現Speak方法
func (s *StartRepo) Speak(message string) string {
//使用注入的IDb訪問數據庫
//s.Source.DB().Where("name = ?", "jinzhu").First(&user)
return fmt.Sprintf("[Repository] speak: %s", message)
}
這樣我們就簡單完成了數據庫訪問層的接口封裝
業務邏輯層service
- 定義IStartService接口
//IStartService 定義IStartService接口
type IStartService interface {
Say(message string) string
}
- 實現IStartService接口方法,注入IStartRepo數據訪問層
//StartService 注入IStartRepo
type StartService struct {
Repo repository.IStartRepo `inject:""`
}
//Say 實現Say方法
func (s *StartService) Say(message string) string {
return s.Repo.Speak(message)
}
控制器controller
- 注入IStartService業務邏輯層,並調用Say方法
//Index 注入IStartService
type Index struct {
Service service.IStartService `inject:""`
}
//GetName 調用IStartService的Say方法
func (i *Index) GetName(ctx *gin.Context) {
var message = ctx.Param("msg")
ctx.JSON(200, i.Service.Say(message))
}
注入gin中
到此三個層此代碼已寫好,然后我們使用"github.com/facebookgo/inject"
Facebook的工具包將它們注入到gin中。
func Configure(app *gin.Engine) {
//controller declare
var index controller.Index
//inject declare
db := datasource.Db{}
//Injection
var injector inject.Graph
err := injector.Provide(
&inject.Object{Value: &index},
&inject.Object{Value: &db},
&inject.Object{Value: &repository.StartRepo{}},
&inject.Object{Value: &service.StartService{}},
)
if err != nil {
log.Fatal("inject fatal: ", err)
}
if err := injector.Populate(); err != nil {
log.Fatal("inject fatal: ", err)
}
//database connect
err = db.Connect()
if err != nil {
log.Fatal("db fatal:", err)
}
v1 := app.Group("/")
{
v1.GET("/get/:msg", index.GetName)
}
}
有關更多的github.com/facebookgo/inject使用方法請參考文檔