普通网友 2019-07-14 03:58
浏览 154
已采纳

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

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 2019-07-14 04:58
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效