Gin Installation

Step 0 - Prerequisites

Make sure you have go installed and available on your terminal, If not, follow our Installing Go tutorial for help

Step 1 - Make a new Go project

Open up a new terminal, and run these commands

mkdir <project-name>
cd <project-name>
go mod init testgin 
ℹ️
Replace <project-name> with your project’s name and testgin with whatever you want to name your go module.

Step 2 - Add gin to the project

go get github.com/gin-gonic/gin

Now the file structure should look like this.

    • go.mod
    • go.sum
  • Step 3 - Create a new main.go file

    touch main.go

    and put in the following,

    main.go
    package main
    
    import "github.com/gin-gonic/gin"
    
    func main() {
        r := gin.Default()
        r.GET("/echo", func(c *gin.Context) {
            c.JSON(200, gin.H{
                "message": "http server works!",
            })
        })
        r.Run() // default address and port: 0.0.0.0:8080
    }

    Step 4 - Run the server and verify

    In the same directory, run,

    go run .

    This should produce an output like this,

    [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
    
    [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
     - using env:	export GIN_MODE=release
     - using code:	gin.SetMode(gin.ReleaseMode)
    
    [GIN-debug] GET    /echo                     --> main.main.func1 (3 handlers)
    [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
    Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
    [GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
    [GIN-debug] Listening and serving HTTP on :8080

    You may notice the HTTP route that we made as GET /echo

    Open up http://localhost:8080/echo on a web browser to confirm if it works.

    This should show up on the browser, if everything is correct.

    Golang Gin HTTP Framework Install Successful Image

    Last updated on