Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Folder structure and package naming convention for a REST API develop in Gin Framework

Tags:

go

go-gin

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 snake 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)?

like image 708
Trevor. W Avatar asked Oct 20 '25 16:10

Trevor. W


1 Answers

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{}, //DO 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.

like image 121
Jacob Lambert Avatar answered Oct 23 '25 06:10

Jacob Lambert