DEV Community

Cover image for Code Your First Rest API in Golang
Gaurish Sethia
Gaurish Sethia

Posted on

Code Your First Rest API in Golang

#go

This tutorial would explain you about how you're going to code a basic rest api in golang,
We'd be using gin a http web server framework.

Let's begin.

Getting Started

Open up your shiny Terminal,
Run the Commands

go mod init gin-tutorial
touch main.go
go get -u github.com/gin-gonic/gin
Enter fullscreen mode Exit fullscreen mode

Terminal

Now, Let's Navigate to our main.go and start writing code with vscode

On top of the file, Describe the package

package main
Enter fullscreen mode Exit fullscreen mode

Now, We'd be importing gin,

package main

import "github.com/gin-gonic/gin"
Enter fullscreen mode Exit fullscreen mode

Make sure you install gin via the command go get -u github.com/gin-gonic/gin

Now, We'll start making our router,

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.SetTrustedProxies([]string{"192.168.1.2"})
    r.Run()
}
Enter fullscreen mode Exit fullscreen mode

Read more about setTrustedProxies here

So, If we run go run main.go, This is what we're gonna get...

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080

Enter fullscreen mode Exit fullscreen mode

Now, Open up localhost:8080 on your browser, You'd see a 404 page not found response, Yes, Because we haven't created any routes yet.

Creating Routes

Get Requests

  • Get requests are handled as .GET, Same applies for all types of requests, Just replace GET with the type of Request,

Let's create a test route:

r.GET("/get", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "status": "healthy",
        })
    })
Enter fullscreen mode Exit fullscreen mode

So, If you now navigate to localhost:8080/get, You see a JSON Response

{"status":"healthy"}
Enter fullscreen mode Exit fullscreen mode

Perfect!

Congratulations, You Just Learned to Create Your First Rest API With Golang.

Top comments (0)