DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Matija Krajnik
Matija Krajnik

Posted on • Updated on • Originally published at letscode.blog

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()
}
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/server/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

Top comments (2)

Collapse
 
dandus989 profile image
Daniel

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

Collapse
 
matijakrajnik profile image
Matija Krajnik Author

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

Our newest Hackathon

Join the DEV x MongoDB Atlas Hackathon 2022 and use your ingenuity and creativity to build an application using MongoDB's cloud based developer data platform, MongoDB Atlas.

โ†’ Get Started