DEV Community

Matija Krajnik
Matija Krajnik

Posted on • Updated on • Originally published at

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

Content of inernal/server/server.go:

package server

func Start() {
  router := setRouter()

  // Start listening and serving requests
Enter fullscreen mode Exit fullscreen mode

Content of internal/server/router.go:

package server

import (

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

Top comments (2)

dandus989 profile image
Daniel Chan

Should "Content of internal/router.go:" be "Content of internal/server/router.go:" This is what the last picture of project directories shows.

matijakrajnik profile image
Matija Krajnik

Yes, you are right. I corrected it. Thanks!