GIN
Get the most from the Gin HTTP framework
Discover how you can write secure and powerful HTTP-based services with the help of Mihalis Tsoukalos, a bit of Go and the Gin framework.
OUR EXPERT iis a systems engineer and a technical writer. He is the author of
Go Systems Programming and
Mastering Go, 3rd edition. You can reach him at
www. mtsoukalos.euand
@mactsouk.
Calm down vicar. The gin we’re talking about is an open source web framework (a collection of libraries and APIs) written in Go that can help you develop powerful HTTP services. All the code discussed here can be found in the https://github.com/mactsouk/LXF.285 GitHub repository. If you want to download all the code for this tutorial from GitHub then you’ll need to run the following three commands:
You need to run cd LXF.285 to go into that directory. We’re now ready to continue with the rest of the tutorial.
A basic server
One of the files found in the repository is called introGin. go and is located inside the /simple directory. introGin. go implements a simple HTTP server and is going to be used in this section to help you understand how to create projects with Gin. The important code in introGin. go is the following:
The first statement creates an Engine instance (with the Logger and Recovery middleware already attached) whereas the second one starts the HTTP server at the port number stored in the PORT string variable ( :8008 ). If you don’t specify the address the server will listen to, it’ll listen to all available network interfaces.
Because this is an empty web site, it does nothing and no URL can be served by it. Nevertheless, Gin works and the web server starts at the desired port number. Running introGin.go from within the simple directory requires executing the following commands:
Note that go mod init and go mod tidy should be executed only once to enable Go modules. Also, feel free to delete go.mod and go.sum at any time and recreate them. The go mod init and go mod tidy commands should be executed inside each directory of the GitHub repository before executing the relevant Go source files.
This shows the debug output when interacting with HTTPmethods. go. When a URL and HTTP method combination isn’t supported, the output shows a 404 HTTP code. Otherwise, it’s a 202 HTTP code.
There are two ways to test introGin.go. The first one uses a web browser and the second one involves a CL utility such as curl or wget. We’re going to discuss both Firefox and curl. When tested with Firefox (http:// localhost:8008/), introGin.go sends the 404 page not found message back because it has no support for any URL. Testing it with curl produces this output: