DEV Community

Cover image for Golang Web API Course: Create starter project with a simple health check endpoint
Hamed Naeemaei
Hamed Naeemaei

Posted on • Edited on

Golang Web API Course: Create starter project with a simple health check endpoint

After I explained the project structure in the previous section, we can create the project and get into the code environment.

Requirements

Before this, we should setup the environment, so follow these steps:

  1. I'm using VSCode as the development IDE so you should install VSCode or another IDE/code editor.

  2. After choosing your IDE, we should install golang from this link.
    To check if golang was installed or not run go version command.

  3. So to use golang debug tools, we should install DELVE with go install github.com/go-delve/delve/cmd/dlv@latest command

  4. (Optional) If you are not familiar with golang and using VSCode, you can install some of this VSCode extensions to develop and debug easier with golang:
    code --install-extension aaron-bond.better-comments
    code --install-extension christian-kohler.path-intellisense
    code --install-extension ckolkman.vscode-postgres
    code --install-extension cweijan.vscode-redis-client
    code --install-extension donjayamanne.githistory
    code --install-extension esbenp.prettier-vscode
    code --install-extension formulahendry.code-runner
    code --install-extension golang.go
    code --install-extension HookyQR.beautify
    code --install-extension IBM.output-colorizer
    code --install-extension mhutchie.git-graph
    code --install-extension ms-azuretools.vscode-docker
    code --install-extension PKief.material-icon-theme
    code --install-extension premparihar.gotestexplorer
    code --install-extension streetsidesoftware.code-spell-checker
    code --install-extension VisualStudioExptTeam.vscodeintellicode
    code --install-extension vscode-icons-team.vscode-icons
    code --install-extension wmaurer.change-case

Create project

Initialize module

At this moment, we need to create our project module in src directory (not in root dir) with go mod init github.com/naeemaei/golang-clean-web-api command.

Install gin package

To install gin package run these command: go get -u github.com/gin-gonic/gin. After the installation is finished go.mod and go.sum files should updated.

Create a health check simple handler

Go to src/api/handlers directory and create health.go file (see here) as in the example below :

package handlers

import (
    "net/http"

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

type HealthHandler struct {
}

func NewHealthHandler() *HealthHandler {
    return &HealthHandler{}
}

func (h *HealthHandler) Health(c *gin.Context) {
    c.JSON(http.StatusOK, "Working!")
}
Enter fullscreen mode Exit fullscreen mode

This file has a constructor to initiate HealthHandler in the router package and can have one or more methods to handle HTTP requests.

Create health router

Go to src/api/routers directory and create health.go file as in the example below:

package routers

import (
    "github.com/gin-gonic/gin"
    "github.com/naeemaei/golang-clean-web-api/api/handlers"
)

func Health(r *gin.RouterGroup) {
    handler := handlers.NewHealthHandler()

    r.GET("/", handler.Health) // Call hanlder.Health method
}
Enter fullscreen mode Exit fullscreen mode

This file instantiates a new handler and call methods based on route and HTTP verbs.

Config web server

Now it's time to config the web server. For this, we need to create api.go file in src/api:

package api

import (
    "github.com/gin-gonic/gin"
    "github.com/naeemaei/golang-clean-web-api/api/routers"
)

func InitServer() {
    r := gin.New()
    r.Use(gin.Logger(), gin.Recovery())

    v1 := r.Group("/api/v1/")
    {
        health := v1.Group("/health")
        routers.Health(health)
    }

    r.Run(":5005")
}
Enter fullscreen mode Exit fullscreen mode

As you can see in this file, after creating the web server we added two gin default middlewares including logger middleware to logging requests and recovery to handle internal panics.
Then create a router group api/v1 and assign health handler to health route. Finally, run the web server on the 5005 port.

Create main.go file

the main.go file is the start point of each golang project.
Go to src/cmd directory and create main.go file here with this content:

package main

import "github.com/naeemaei/golang-clean-web-api/api"

func main(){
    api.InitServer()
}
Enter fullscreen mode Exit fullscreen mode

In the next section, using Viper to make project environment configuration

Now we can run the project and test the health check endpoint, first go to main.go file and press F5 to run. If everything is okay you can test http://localhost:5005/api/v1/health/ url to check health check works or not, but if didn't run we need to create launch.json in VSCode.

Run golang project
Of course, if you are familiar with it, it is better to make the launch.json, and if not, I will explain it to you further

Golang project launch.json in VSCode

On the root create a .vscode directory then go to it and create launch.json file(see here) with this content (Of course, there is an easier way for it, if you are a beginner, you may make a error):

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}/src/cmd"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)