DEV Community

Madhav Jha
Madhav Jha

Posted on

A simple golang web server using awesome echo

#go

If you are like me and used golang at some point in the past and haven't kept up with the language changes, the most significant change has been the introduction of go modules.

A very good introduction is available here. But the TLDR version is as follows.

In a new directory, create a file main.go.

package main

import (
    "net/http"

    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func main() {
    // Echo instance
    e := echo.New()

    // Middleware
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    // Routes
    e.GET("/", hello)

    // Start server
    e.Logger.Fatal(e.Start(":1323"))

}

func hello(c echo.Context) error {
    return c.String(http.StatusOK, "hello world")
}

Run the following commands inside the directory.

go mod init example.com/hello
go get github.com/labstack/echo/v4

This will create files go.mod and go.sum which are similar to package.json and package-lock.json in node/npm world.

At this point you are ready to build. Note the binary built is called hello which is what you called the package.

go build .
./hello

Top comments (0)