DEV Community

loading...

Structure project directories

Matija Krajnik
QA automation engineer experienced in writing GUI automated tests for Web and Mobile apps, Web REST API automated tests, load/performance tests, and developing custom testing tools from scratch.
Originally published at letscode.blog Updated on ・1 min read

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()
}
Enter fullscreen mode Exit fullscreen mode

Content of inernal/server/server.go:

package server

func Start() {
  router := setRouter()

  // Start listening and serving requests
  router.Run(":8080")
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Now our project directories looks like on picture below.

Structured project directories

Discussion (0)