YouTube Video:

How to start with gin framework


    Hello friends! In this post, I will be discussing about how to start with Gin framework. First of all, you have to install the latest version of Golang. Now, create a folder myApp and open it your favourite IDE. I am using VS Code. Enter into the folder in the terminal. You can use below command to enter into a folder if needed:

cd <Folder_Name>

Now, run below command to initialise the module:

go mod init <Module_Name>

Now, create a file main.go and import the below package inside it.

"github.com/gin-gonic/gin"

    Till now, you main.go file should look like below:


package
main
import "github.com/gin-gonic/gin"

Now, you can run below command:

go mod tidy

Now, we will define controller functions:

func helloGin(ctx *gin.Context) {
ctx.String(200, "Hello Gin")
}


func about(ctx *gin.Context) {
ctx.String(200, "This is About Us page")
}


func contact(ctx *gin.Context) {
ctx.String(200, "This is Contact Us page")
}


Here, You can notice one thing is, we are using an input of *gin.Context in each case. It is a mandatory input in controller function in Gin application.

Now, we will define routers. We will define them inside main function before calling the Run() function.

func main() {
app := gin.Default()


app.GET("/", helloGin)
app.GET("/about", about)
app.GET("/contact", contact)


app.Run("localhost:8081")
}

The whole code is like below:

package main

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

func helloGin(ctx *gin.Context) {
ctx.String(200, "Hello Gin")
}

func about(ctx *gin.Context) {
ctx.String(200, "This is About Us page")
}

func contact(ctx *gin.Context) {
ctx.String(200, "This is Contact Us page")
}

func main() {
app := gin.Default()

app.GET("/", helloGin)
app.GET("/about", about)
app.GET("/contact", contact)

app.Run("localhost:8081")
}

That's it guys! We are done. You can simply run below command to start the application.

go run main.go

Now, you can go to your favourite browser and hit the below urls to see the results:

localhost:8081

localhost:8081/about

localhost:8081/contact

 YouTube Video:

How to start with gin framework