Golang Gin
Overview
Applications are built using one of two architectures: monolithic or microservices. Golang uses a microservices architecture for developing applications, which makes it fast and easy to maintain on a large scale. Go has different frameworks for developing RESTful modern microservices, and in this article, we will learn about the Gin framework, which is a modern framework in Go.
Prerequisites
- Basic command of the Golang programming language.
- Install git on your computer and VScode.
What is Gin?
Golang gin is a high-performance HTTP web framework ritten in Golang. It's becoming increasingly popular in the Go-community. Compared to other frameworks such as Martini (used for writing modular web applications and services in Golang.), it's 40 times faster. Go Gin has some common functions like middleware support, rendering, and so on, which are introduced to reduce time and use boilerplate for simpler web applications.
Why Gin?
The reason to choose Go gin over any other framework is:
- The performance of Go gin is faster than any web framework in golang as it contains radix tree-based routing and has a small memory footprint. There is no reflection. As reflection makes the code complex.
- It is useful to parse and validate JSON, for example, by ensuring that all necessary values are there.
- Gin makes it easy to collect all of the errors that occur during an HTTP request.
- It helps in organising routes and nesting the API functions will never degrade the performance.
Installation
Download and install:
Import into the code:
Example
Output for the above code:
Explanation of the above code:
- In the above code, we are creating a simple web server using the gin framework where we are using gin. default()which creates a Gin router with default middleware.
- Next, we are creating a get handler using router.GET(path, handle) , where path is the relative path and the second parameter is the function handler which takes gin. Context as an argument. The handler function responds with a JSON response with the status 200.
- Finally, we use a router to start the router.Run("localhost:8080") listens on port 8080 by default.
gin.New vs gin.Default
Routers can be initialized in two ways: with gin.New() and with gin. Default(). To establish the router engine in the above example, we called gin.Default(). Let's compare the two.
gin.New() creates a blank engine with default settings. The default configuration is as below.
- RedirectTrailingSlash: true
- RedirectFixedPath: false
- HandleMethodNotAllowed: false
- ForwardedByClientIP: true
- UseRawPath: false
- UnescapePathValues: true
gin.Default() internally, creates an engine using gin.New(). It also includes des logger and recovery middleware.
Developing a RESTful API with Go and Gin
Create a folder for your code
To create the folder follow the process:
On Linux or Mac:
On Windows:
Using the cmd, create a directory for your code name as gin-services.
Design API Endpoints
We will build an API that is used for buyincoursessaat scaler. So you’ll need to provide endpoints through which a we can get and addcoursese for users.
When developing an API, you typically begin by designing the endpoints. Your API’s users will have more success if the endpoints are easy to understand.
Here are the endpoints you’ll create in this tutorial.
Write a Handler to Add a New Item
When the client makes a POST request at /course, you want to add the course described in the request body to the existing course data.
To do this, you’ll write the following:
- Logic to add the new course to the existing list.
- A bit of code to route the POST request to your logic.
Add the following code below the import statements. (The end of the file is a good place for this code, but Go doesn’t enforce the order in which you declare functions.)
In the above code,
- We are using Context.
- BindJSON is used to connect the request body to newCourse.
- Add the course struct that was created from the JSON to the course slice using append.
- Include a 201 status code in the response and JSON indicating the course you've added.
Update your main function code so that it contains the router. POST method, as in the following.
In this code, you will:
- Create the POST method at the /course path to the postCourse function.
- Gin allows you to associate a handler with an HTTP method and path combination. You can then route requests delivered to a single path differently depending on the approacclient is approach main. Go.
Start the server:
Make a POST request to the server using curl request:
Response from the server:
Next, create a module that can manage project dependencies.
Run the go mod init command, which helps to locate the path for whatever your code module will add.
- This command generates a go. mod file in which any new dependencies will be listed for tracking.
- Now, we need to create the data and to keep it minimal and simple we will store data in memory.
Create main. Go file,
Next, we’ll write code to implement your first endpoint.
Write a Handler to Return All Items
When the client makes a GET /course request, you want to return all of the courses as JSON.
To accomplish this, write the following:
- To prepare a response, as JSON data.
- Code to map the request path to your logic.
Code for this:
To get the course list, paste the following code below the struct code you added in the previous section.
This getCourse function generates JSON from a slice of course structs and writes it to the response.
In the above code, we:
- Create a getCourse function that accepts a gin as an argument.
- gin. Context is the most significant aspect of Gin. It stores request information and verifies and serializes JSON. (Despite the name, this is not the same as Go's built-in context package.)
- Call Context.IndentedJSON to convert the struct into JSON format and add it to the response.
- The first argument to the function is the HTTP status code you want to transmit to the client. You're passing the net/http package's StatusOK constant here to signify 200 OK.
Note: You can replace Context.IndentedJSON with a call to Context.JSON to send a more compact JSON. In practice, the indented form is much easier to work with when debugging and the size difference is usually small.
- Near the top of main. go, just below the course declaration, paste the code below to assign the handler function to an endpoint path.
- This sets up an association in which getCourse handles requests to the /course endpoint path.
In the above code,
- Use Default to set up a Gin router.
- To correlate the GET HTTP method and the /course path with a handler function, use the GET function.
- Take note that you're passing the getCourse function's name. This differs from sending the function's output, which you would do by using getCourse() (note the parenthesis).
- To connect the router to an http.Server and start the server, use the Run method.
- Save main.go.
Run the server:
Make a get request to the server
Response from the server:
To automatically run the code or start the server we have something called CompileDaemon,
Command to install:
After that run:
Scaler is the .exe file. You can check by visiting the go. mod file, the first line will be something like
And you are done!
Write a handler to return a specific item
We want to return the course whose ID matches the id path parameter when the client requests GET /course/[id].
To accomplish this, we will:
- Create logic to fetch the desired course.
- Connect the path to the rationale.
To obtain a specific course, insert the following code below the postCourses function you added in the prior section.
This function will extract the ID from the request path and then find a course that matches it.
Write the code:
Finally, add the router. GET, where the path is now /courses/:id, as shown in the following example.
Associate the /courses/:id path with the getCourseByID function. In Gin, the colon indicates that this is the path for a particular item id.
Next,
- Save main.go.
- Start the server
Make a GET request using the curl command
Response from the server
Write a Handler to Update a Specific Item
We want to update the course whose ID matches the id path parameter when the client requests PUT /course/[id].
To accomplish this, we will:
- Create logic to fetch the desired course.
- Update the course.
To update a specific course, insert the following code below the getCourseByID function you added in the prior section.
This function will extract the ID from the request path. Then, it will update the course with the new data provided with the request.
Write the code:
Finally, add the router. PUT, where the path is now /courses/:id, as shown in the following example.
Associate the /courses/:id path with the getCourseByID function. In Gin, the colon indicates that this is the path for a particular item id.
Next,
- Save main.go.
- Start the server
Make a POST request to the server using curl request:
Response from the server:
Write a Handler to Delete a Specific Item
We want to delete the course whose ID matches the id path parameter when the client requests DELETE /course/[id].
To accomplish this, we will:
- Create logic to find the desired course.
- Delete the course.
To delete a specific course, insert the following code below the updateCourseByID function you added in the prior section.
This function will extract the ID from the request path. Then, it will delete the course with the same ID.
Write the code:
Finally, add the router.DELETE, where the path is now /courses/:id, as shown in the following example.
Next,
- Save main.go.
- Start the server
Make a POST request to the server using curl request:
This deletes the course with ID:3.
Complete Code:
Congratulations! You’ve just used Go and Gin to write a simple RESTful web service.
Conclusion
- In this article, we learned a comprehensive explanation of what Go Gin is, its features, and its advantages as a web framework in Golang.
- We also get to know why Go Gin stands out and is a better choice.
- A step-by-step guide on how to create RESTful APIs in Golang using the Go Gin framework, covering topics such as endpoint creation, request handling, and response generation.
Thank you for your time. I hope you found this information useful.