普通网友 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.

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献