DEV Community

Matija Krajnik
Matija Krajnik

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

Starting Gin server

First we need to give our Web App a name. We will be making a simple blog, so let's call it RGB (React Gin Blog).

We will start by making project root directory inside of ~/go/src and making it our current working directory.

cd ~/go/src
mkdir rgb
cd rgb
Enter fullscreen mode Exit fullscreen mode

Our first dependency is Gin framework. You can download it by running go get github.com/gin-gonic/gin if you don't have it already.
Before writing our first backend source file, we need to crate go.mod file in project root directory needed by Golang to find and import required dependencies. Content of that file will for now be:

module rgb

go 1.16

require github.com/gin-gonic/gin v1.6.3
Enter fullscreen mode Exit fullscreen mode

Now let's make our app entry point, main.go file:

package main

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

func main() {
  // 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{}) })

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

And that's it. We can now start our server by running:

go run main.go
Enter fullscreen mode Exit fullscreen mode

Verify that server is running by opening localhost:8080/api/hello in your favorite web browser. If server is working you will see {"msg":"world"}.

Oldest comments (2)

Collapse
 
travistennies profile image
Travis Tennies

Very good. It would be nice if the file structure was more obvious. Guessing "rgb" is the root dir for the entire project.? Also there were no instructions how to create the go.mod file.

Collapse
 
cnash profile image
Chris Nash • Edited

Don't you need to add "net/http" to the imports?

Otherwise, http.StatusNotFound is unknown.