React Gin Blog (4/19): Structure project directories

It’s always good practice to separate your code based on what every part is doing, so it’s easier to find relevant part later on, so we will do just that before going further. In root project directory we will create new directories cmd/rgb/ and we will move our main.go file there. That will be entry point for our app.
Also, we will create directories internal/server/ and there add new file server.go where Gin server will be started. Function for starting server will be called from main.go. We will also move router setup to its own file internal/server/router.go. Let’s look at our files now.

Content of cmd/rgb/main.go:

package main

import "rgb/internal/server"

func main() {
  server.Start()
}

Content of inernal/server/server.go:

package server

func Start() {
  router := setRouter()

  // Start listening and serving requests
  router.Run(":8080")
}

Content of internal/router.go:

package server

import (
  "github.com/gin-gonic/gin"
)

func setRouter() *gin.Engine {
  // Creates default gin router with Logger and Recovery middleware already attached
  router := gin.Default()

  // Create API route group
  api := router.Group("/api")
  {
    // Add /hello GET route to router and define route handler function
    api.GET("/hello", func(ctx *gin.Context) {
      ctx.JSON(200, gin.H{"msg": "world"})
    })
  }

  router.NoRoute(func(ctx *gin.Context) { ctx.JSON(http.StatusNotFound, gin.H{}) })

  return router
}

Now our project directories looks like on picture below.

Structured project directories

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: