Logo

dev-resources.site

for different kinds of informations.

Gin and router example

Published at
7/8/2024
Categories
go
gin
beginners
backend
Author
hieunguyendev
Categories
4 categories in total
go
open
gin
open
beginners
open
backend
open
Author
13 person written this
hieunguyendev
open
Gin and router example

Image description

  • Install Gin with the following command:
go get -u github.com/gin-gonic/gin
Enter fullscreen mode Exit fullscreen mode
  • After installation, we proceed to code in the β€œmain.go” file with a simple function as follows:
package main

import (
  "net/http"

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

func main() {
  r := gin.Default()
  r.GET("/ping", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      "message": "pong",
    })
  })
  r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Enter fullscreen mode Exit fullscreen mode
  • Then run the main file with the following command:
go run cmd/server/main.go
Enter fullscreen mode Exit fullscreen mode

Note: Depending on your folder organization, the command to run the main.go file may differ from mine. I have introduced how to organize the structure in the article: here

  • After running the above command, we will receive the following result:

Image description

  • Great, let's try calling the ping endpoint with the following command:
curl http://localhost:8080/ping
Enter fullscreen mode Exit fullscreen mode
  • The result received will be:

Image description

  • Now, let's try to split the simple router:
package main

import (
    "net/http"

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

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

    v1 := r.Group("/v1")
    {
        v1.GET("/ping", Pong) // curl http://localhost:8080/v1/ping
    }
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

func Pong(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
        "message": "pong",
    })
}

Enter fullscreen mode Exit fullscreen mode

Note: After changing the code as above, remember to run the command: "go run cmd/server/main.go" to apply the new code.

  • Next, let's try running the new router with the following command:
curl http://localhost:8080/v1/ping
Enter fullscreen mode Exit fullscreen mode
  • The result received will be:

Image description

  • Now, let's try to get the parameter from Param:
package main

import (
    "net/http"

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

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

    v1 := r.Group("/v1")
    {
        v1.GET("/ping/:name", Pong) // curl http://localhost:8080/v1/ping
    }
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

func Pong(c *gin.Context) {
    name := c.Param("name")
    c.JSON(http.StatusOK, gin.H{
        "message": "pong:::: " + name,
    })
}

Enter fullscreen mode Exit fullscreen mode

Note: After changing the code as above, remember to run the command: "go run cmd/server/main.go" to apply the new code.

  • Try to get the param with the following command:
curl http://localhost:8080/v1/ping/hieunguyen
Enter fullscreen mode Exit fullscreen mode
  • The result received will be:

Image description

  • Next, we will try to get the parameter from the Query:
package main

import (
    "net/http"

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

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

    v1 := r.Group("/v1")
    {
        v1.GET("/ping", Pong) // curl http://localhost:8080/v1/ping
    }
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

func Pong(c *gin.Context) {
    id := c.Query("id")
    c.JSON(http.StatusOK, gin.H{
        "message": "pong:::: " + id,
    })
}

Enter fullscreen mode Exit fullscreen mode

Note: After changing the code as above, remember to run the command: "go run cmd/server/main.go" to apply the new code.

  • Try to get the query with the following command:
curl http://localhost:8080/v1/ping\?id=12345
Enter fullscreen mode Exit fullscreen mode
  • The result received will be:

Image description

You can directly refer to Gin on GitHub with the following link:here

Give me a reaction and a follow for motivation 😘

If you found this article useful and interesting, please share it with your friends and family. I hope you found it helpful. Thanks for reading πŸ™

Let's get connected! You can find me on:

gin Article's
30 articles in total
Favicon
Developing a Simple RESTful API with Gin, ginvalidator, and validatorgo
Favicon
Go's Concurrency Decoded: Goroutine Scheduling
Favicon
πŸš€ Building a RESTful API in Go: A Practical Guide
Favicon
A Deep Dive into Gin: Golang's Leading Framework
Favicon
Building a Blog API with Gin, FerretDB, and oapi-codegen
Favicon
How to enable hot reload in your Gin project
Favicon
Implementing an Order Processing System: Part 1 - Setting Up the Foundation
Favicon
Gin and router example
Favicon
How to Upload Images to AWS S3 with Golang
Favicon
Basic CRUD Operations Using Golang, Gin Gonic, and GORM
Favicon
Simplifying User Management with GIN and MongoDB
Favicon
Gin + Gorm Practical Guide, Implementing a Simple Q&A Community Backend Service in One Hour
Favicon
A Beginner-friendly Approach to Developing a REST API with Go, Gin and MSQL
Favicon
Cara menggunakan Cobra untuk menjalankan server Golang Gin
Favicon
A Beginner-friendly Approach to Developing a REST API with Go and Gin
Favicon
Easily build a simple and reliable ordering system in an hour using go efficiency tools
Favicon
Example 5, Automatically generate grpc gateway service project code, easy to achieve cross-service grpc calls
Favicon
Example 3, Automatically generate generic web service (gin) project code, increasing development efficiency by at least 1x
Favicon
Example 6, Build a simple golang e-commerce microservices framework step by step using tool
Favicon
Building a simple API with Golang using Gin-gonic
Favicon
Golang Web API: Project configuration management using Viper
Favicon
Golang Web API Course: Create starter project with a simple health check endpoint
Favicon
API validation in Gin: Ensuring Data Integrity in Your API
Favicon
Using the tool to complete the conversion of a community back-end single service to a microservice cluster in one day
Favicon
A secret weapon to improve the efficiency of golang development, a community backend service was developed in one day
Favicon
Play Microservices: Api-gateway service
Favicon
Set up a Stripe Checkout REST API (+ metadata) using Go and Gin Framework.
Favicon
Go: CRUD API using Gin Framework
Favicon
Example 1, Automatically generate a complete gin+gorm+redis+CRUD web service project without writing a line of Go code
Favicon
Not a Go LiveView developer yet? Try to guess what this code is doing, though.

Featured ones: