Let's get straight to the business with some minimal introduction and motivation.
A web framework makes the life of a backend developer easier. If you want to set up a server in Go, you have a handful of options:
and the list goes on...
httprouter is a fast router for Go that implements a lot of features of which a few are Path auto-correction, Zero Garbage, Best Performance.
Why not use httprouter?
Although httprouter provides a lot of these features in routing, it's not a complete framework i.e. it does not provide features that improve developer experience like middleware.
So, gin it is
With gin, it's simple and we get more features like adding middleware later on for authentication, logging and authorization. Without further ado, let's go
:
Create a folder
gin-server
in your$GOPATH
and enter the foldergin-server
Initiate go modules using the command in your shell:
go mod init
- Import
gin
using the command in your shell:
go get -u github.com/gin-gonic/gin
Create a file named main.go
with the following contents
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// initiates a gin Engine with the default logger and recovery middleware
router := gin.Default()
// sets up a GET API in route /hello that returns the text "World"
router.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "World",
})
})
// Run implements a http.ListenAndServe() and takes in an optional Port number
// The default port is :8080
router.Run()
}
Now, we're ready to go
!
All we need is to run the server with the command in the project directory
go run main.go
We should see these logs on the terminal
Open your favorite browser and enter the address to see the response of the API we built
Yes, we're done! 🎉
We've set up an HTTP Server with the gin
framework. In the future, expect articles on connecting to Databases, best practices, authentication, middleware, and more. 🤟
Top comments (0)