DEV Community

Cover image for Creating an HTTP server in Go using gin
Udaya Prakash
Udaya Prakash

Posted on

Creating an HTTP server in Go using gin

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:

  1. httprouter
  2. beego
  3. fasthttp
  4. gin

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 folder gin-server

  • Initiate go modules using the command in your shell:

go mod init
Enter fullscreen mode Exit fullscreen mode
  • Import gin using the command in your shell:
go get -u github.com/gin-gonic/gin
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

We should see these logs on the terminal
Go run logs

Open your favorite browser and enter the address to see the response of the API we built

Testing API in Browser

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. 🤟

Discussion (0)