Skip to main content

Go API Framework

Go frameworks (Gin, Fiber, Echo)

Gin — Fast, Minimal, Industry Favorite​

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "pong"})
})
r.Run()

Fiber — Express.js–Style, Ultra Fast​

app := fiber.New()
app.Get("/ping", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"message": "pong"})
})
app.Listen(":3000")

Echo — Clean APIs, Structured Middleware​

e := echo.New()
e.GET("/ping", func(c echo.Context) error {
return c.JSON(200, map[string]string{"message": "pong"})
})
e.Start(":8080")

Let's Build a Simple Go API with Gin

Request Flow (Important)​

HTTP Request
↓
Gin Router
↓
Handler (HTTP)
↓
Service (Business Logic)
↓
Repository (Data)
↓
Domain Model

Folder Structure​

my-api/
├── cmd/
│ └── api/
│ └── main.go
│
├── internal/
│ ├── app/
│ │ ├── server.go
│ │ ├── router.go
│ │ └── middleware.go
│ │
│ ├── config/
│ │ └── config.go
│ │
│ ├── domain/
│ │ └── user.go
│ │
│ ├── service/
│ │ └── user_service.go
│ │
│ ├── repository/
│ │ └── user_repository.go
│ │
│ ├── handler/
│ │ ├── user_handler.go
│ │ └── health_handler.go
│ │
│ └── platform/
│ └── database/
│ └── postgres.go
│
├── go.mod
└── README.md

Tools​

  • IDE: Visual Studio Code
  • Official Go Extension: Go (by Google)

Extra VS Code Extensions (Go Stack)​

PurposeExtension
Go language supportGo (official)
REST testingREST Client
API testingThunder Client
Docker supportDocker
Git UIGitLens
YAML / OpenAPIYAML

Getting Started​

Step 1: Initialize Go Module​

mkdir my-api && cd my-api
go mod init my-api
mkdir cmd\api
mkdir internal
type nul > cmd\api\main.go
go get github.com/gin-gonic/gin

Step 2: Edit the main.go File​

package main

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

func main() {
r := gin.Default()

r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{
"status": "ok",
})
})

r.Run(":8080")
}

Step 3: Run the API Server​

Run where the main.go file is located:

go run .

Checkpoint: Open up your browser and navigate to localhost:Port, then localhost:Port/health

You should see the following JSON response

{
"status": "ok"
}