Technology Capabilities
Technology CapabilitiesI’m Janki Makwana, a Data Scientist at GlobalLogic. I have been working with a major re...
Welcome to the second part of our two-part series on the evolving payment industry! In ...
GlobalLogic provides unique experience and expertise at the intersection of data, design, and engineering.
Get in touchLearning a new programming language is not easy, but the process is more manageable with proper guidelines and step-by-step instructions.
Go is a powerful and easy to learn language that any programmer can adapt without difficulty. It’s as simple as its name, Go or Golang.
Like most programming languages, Go requires some initial setup. It is important to use Go with Gin, which supports various coding assignments related to building web applications, including web services. To use Go with Gin, we will first project the use of Gin, get request details, and marshal JSON for responses.
Next, we’ll build a REST API server with two endpoints. The project in this example will be a repository of data for event impacts and event moratorium records.
This article includes the following sections:
In this example, we’ll build an API that provides access to a store selling customized t-shirts on “Test Amazon.” We’ll need to build endpoints where a client can retrieve and add t-shirts for users.
When building an API, we generally start by designing the endpoints. Our API’s end-users will have a better experience if the endpoints are easy to use and understand.
The following are the endpoints that we’ll develop in this tutorial for “/tshirts”:
Next, we’ll create a folder structure for our code.
To start creating a folder for our code, we’ll use:
$ cd
C:\> cd %HOMEPATH%
$ mkdir gin-web-service
$ cd gin-web-service
$ go mod init example/gin-web-service
go: creating new go.mod: module example/gin-web-service
We will store test data in the memory instead of the database to avoid complexity. This would mean that the set of t-shirts will not save when we stop the server, and then we would need to recreate it when we restart it.
package main
// tshirt collection.
type tshirt struct {
ID string `json:"id"`
Color string `json:"color"`
Ceremony string `json:"ceremony"`
Price float64 `json:"price"`
}
// tshirts slice to seed test data.
var tshirts = []tshirt{
{ID: "1", Color: "Blue", Ceremony: "ChildBirthday", Price: 56.99},
{ID: "2", Color: "Red", Ceremony: "Anniversary", Price: 17.99},
{ID: "3", Color: "White", Ceremony: "Christmas", Price: 39.99},
}
// gettshirts responds with the list of all tshirts as JSON.
func getTshirts(c *gin.Context) { // gin.Context parameter.
c.IndentedJSON(http.StatusOK, tshirts)
},
func main() {
router := gin.Default()
router.GET("/tshirts", getTshirts)
router.Run("localhost:8080")
}
import (
"net/http"
"github.com/gin-gonic/gin"
)
$ go run // since we have only one executable main.go
$ curl http://localhost:8080/tshirts/2
[
{
"id": "1",
"color": "Blue",
"ceremony": "ChildBirthday",
"price": 56.99
},
{
"id": "2",
"color": "Red",
"ceremony": "Anniversary",
"price": 17.99
},
{
"id": "3",
"color": "White",
"ceremony": "Christmas",
"price": 39.99
}
]
When the client makes a POST request at “/tshirts,” then you want to add the t-shirt described in the request body to the existing t-shirts data.
// postTshirts adds an tshirt from JSON received in the request body.
func postTshirts(c *gin.Context) {
var newTshirt tshirt
// To bind the received JSON to newTshirt, call BindJSON
// Add the new tshirt to the slice.
func main() {
router := gin.Default()
router.GET("/tshirts", getTshirts)
router.POST("/tshirts", postTshirts)
router.Run(“localhost:8080”)
$ go run
$ curl http://localhost:8080/tshirts \
--include \
--header "Content-Type: application/json" \
--request "POST" \
--data '{"id": "4","color": "Yellow","ceremony": "Baby Born","price": 49.99}'
$ curl http://localhost:8080/tshirts \
--header "Content-Type: application/json" \
--request "GET"
And the output would be:
[
{
"id": "1",
"color": "Blue",
"ceremony": "ChildBirthday",
"price": 56.99
},
{
"id": "2",
"color": "Red",
"ceremony": "Anniversary",
"price": 17.99
},
{
"id": "3",
"color": "White",
"ceremony": "Christmas",
"price": 39.99
},
{
"id": "4",
"color": "Yellow",
"ceremony": "Baby Born",
"price": 49.99
}
]
When the client requests to GET “/tshirts/[id],” you want to return the t-shirt that ID matches the ID path parameter.
// getTshirtByID locates the tshirt whose ID value matches the id
// parameter sent by the client, then returns that tshirt as a response.
func getTshirtByID(c *gin.Context) {
id := c.Param("id")
// Loop over the tshirts list, looking for
func main() {
router := gin.Default()
router.GET("/tshirts", getTshirts)
router.GET("/tshirts/:id", getTshirtByID)
router.POST("/tshirts", postTshirts)
router.Run(“localhost:8080”)
$ go run
$ curl http://localhost:8080/tshirts/2
{
"id": "2",
"color": "Red",
"ceremony": "Anniversary",
"price": 17.99
}
The key advantages of Go include:
The disadvantages of Go are:
The following are insights to consider for those who would like to use this language for their project:
Now, you will be able to create Restful web services using Go and Gin and work with other packages based on your needs, such as Io/ioutil, validator.v9, Math, Strconv, Fmt, etc.
All languages can have disadvantages, so it is important to carefully choose which language to use for your project with these potential drawbacks in mind.
HAPPY LEARNING!
A RESTful API in Go and Gin is a set of web endpoints that use HTTP requests and responses created using the Go programming language and the Gin web framework.
Go offers high performance and efficiency, while Gin provides a lightweight framework with robust features for building APIs.
Yes, Gin is user-friendly for beginners, offering a good starting point for learning API development in Go.
Gin is known for its speed, middleware support, routing capabilities, and ability to handle JSON validation and rendering.
Go’s concurrency model, featuring goroutines and channels, allows for handling multiple requests efficiently, making it ideal for scalable API development.