dqegbo2691
dqegbo2691
2019-07-14 03:58

在Gin Framework中开发的REST API的文件夹结构和包命名约定

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

I was a NodeJS / PHP developer and I'm a beginner using Go. After doing a little research, I come up with a MVC style folder structure like this for my REST API project.

.
+- bin/
+- controllers/
   +- userController/
      +- userController.go
+- models/
   +- userModel/
      +- userModel.go
+- main.go

Thus, I can have my code look like this:

import "github.com/gin-gonic/gin"
import "controllers/userController"

router := gin.Default()
router.GET("/user", userController.handleSomeLogicHere)

However, I then realised that it is not recommended to use camel case and snack case for packages according to the GoLang official website.

I am wondering if it is not a good practice to use MVC in Go (because I know some one suggest module/dependency based folder structure)?

Or should I change all controllers and models into one word like usercontroller or userctrl (but it seems like a bit wired to me)?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dqba94619 dqba94619 2年前

    I would change your folder structure a little bit. Instead of having a separate package for each controller, I would instead have those be a part of the controllers package (While I am talking about the controllers, the same line of thinking holds true for the models).

    .
    +- bin/
    +- controllers/
       +- user.go
    +- models/
       +- user.go
    +- main.go
    

    Doing this, I would also change the code structure a bit to instantiate a controller instance like so:

    import "models"
    import "controllers"
    import "github.com/gin-gonic/gin"
    
    userController := controllers.UserController{
        Users: models.UserModel{}, //DI your stuff here
    }
    
    router := gin.Default()
    router.GET("/user", userController.GetUser)
    

    You could go as you were wanting, creating a new package for each controller, but it will easily grow into a large number of packages. By keeping all of the controllers in a single package, it makes it easier to work with.

    Note: As your app grows, there may be a need to create sub packages. One case I can think of is placing all admin only controllers in a controllers/admin package.

    点赞 评论 复制链接分享

为你推荐