# GinProjectStructureExample **Repository Path**: zhangkaichun/gin-project-structure-example ## Basic Information - **Project Name**: GinProjectStructureExample - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-10-12 - **Last Updated**: 2024-10-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # GinProjectStructureExample ## 作者个人对于Gin工程化的项目结构案例: ``` Demo | --app | | | | | --api | | | | | --TestApi.go | | | --model | | | | | --TestModel.go | | | --repository | | | | | --TestRepository.go | | | --service | | | | | --TestService.go | --router | | | | | --routers | | | | ——TestDemoRouter.go | | | --InitRouter.go --main.go | --go.mod | --go.sum ``` ## 结构代码 + main.go ```go package main import "demo/router" func main() { router.InitRouter() } ``` + InitRouter.go ```go package router import ( "demo/router/routers" "github.com/gin-gonic/gin" ) func InitRouter() { r := gin.Default() routers.TestDemoRouter(r) r.Run(":8080") } ``` + TestRouter.go ```go package routers import ( "demo/app/api" "demo/app/repository" "demo/app/service" "github.com/gin-gonic/gin" ) func TestDemoRouter(r *gin.Engine) { // 依赖注入 testRepo := repository.NewTestRepoitory() testService := service.NewTestService(testRepo) api := api.NewTestApi(testService) userGroup := r.Group("/api/test") { userGroup.GET("/hello", api.TestDemoApi) } } ``` + TestApi.go ```go package api import ( "demo/app/service" "github.com/gin-gonic/gin" ) type TestApi struct { testService *service.TestService } func NewTestApi(testService *service.TestService) *TestApi { return &TestApi{testService: testService} } func (ctx *TestApi) TestDemoApi(c *gin.Context) { c.JSON(200, gin.H{ "code": 200, "message": ctx.testService.TestDemoService(), }) } ``` + TestService.go ```go package service import "demo/app/repository" type TestService struct { testRepo *repository.TestRepository } func NewTestService(testRepo *repository.TestRepository) *TestService { return &TestService{testRepo: testRepo} } func (ctx *TestService) TestDemoService() string { return ctx.testRepo.TestDemoRepo() } ``` + TestRepository.go ```go package repository type TestRepository struct { } func NewTestRepoitory() *TestRepository { return &TestRepository{} } func (ctx *TestRepository) TestDemoRepo() string { return "Hello World!!" } ```