DEV Community

Cover image for Go + Echo: The Simple Way to Build a Web Server
Amorto Goon
Amorto Goon

Posted on

Go + Echo: The Simple Way to Build a Web Server

Building a performant API shouldn't feel like a chore. If you're looking for a simple language that is fun and performant, look no further than go. There are a lot of frameworks for GO but today we will be choosing Echo.

TLDR

  • Project Setup: Initializing a Go module
  • Echo Basic: Creating echo instance for route handling with v5
  • Routing: Handling Get Request

Before we begin

In this guide, we will not go over how to install and setup go. It's assumed you already have go installed and configured.

We are also assuming you know basic Go syntax and how to create a simple hello word program.

1. Project setup

To start, we need to initialize a go module in our current working directory. Once you are in a folder where you'd like to build this application, initialize module.

go mod init myserver
Enter fullscreen mode Exit fullscreen mode

Ideally, you'd put your source code location, for example github.com/[your_username]/[repo_name] but for the sake of simplicity we will be using myserver instead.

2. Echo Basic

To use Echo as our framework, we need to create a main package first.

Step 1. Create a file and name it main.go. We can also run the following command to create the file. Make sure we are still on our working directory.

touch main.go
Enter fullscreen mode Exit fullscreen mode

Step 2. Inside main file let's create a simple main function and print hello world.

package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}
Enter fullscreen mode Exit fullscreen mode

Now we can run our application and see Hello World! printed on our terminal.

To run this application,

go run main.go
Enter fullscreen mode Exit fullscreen mode

Step 3. Now that we have a basic working application, we can bring in Echo to create our server.

To install Echo,

go get github.com/labstack/echo/v5
Enter fullscreen mode Exit fullscreen mode

Step 4. After installing Echo successfully we can start creating our API.

After this guide, we want to visit http://localhost:4000/hello and get a json response similar to this.

{
    "message": "Hello World!"
}
Enter fullscreen mode Exit fullscreen mode

To achieve our goal, let's start adding changes to our main.go file.

//main.go

package main

import (
    "net/http" // import net/http for HTTP status codes

    "github.com/labstack/echo/v5" //import echo v5
)

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

    // Define a route for GET requests to "/hello"
    e.GET("/hello", func(c *echo.Context) error {
        return c.JSON(http.StatusOK, map[string]string{
            "message": "Hello World!",
        })
    })

    // Start the server on port 4000 and log any errors that occur
    if err := e.Start(":4000"); err != nil {
        e.Logger.Error("failed to start server", "error", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

We have made quite a bit of changes here. I have made to sure to add comments so we can understand what each chunk of code does even before you get to this line. However, let's a still dive a bit deeper.

  • Initializing Echo: Before we can use any of the functionality that echo provides us, we have to initialize it. We can do so by using echo.New() and importing the echo package github.com/labstack/echo/v5.

  • Get request: In Echo, if we want to create an endpoint we can do so by using the variable where we stored our echo instance. Similarly we can also use e.POST(), e.PUT(), e.DELETE() etc.

  • Returning JSON: To make our endpoint return a json response we have to use c.JSON(). It accepts two parameters, one is the http status code. You might have noticed that we are using go http package to return the status code, you can also use 200 instead of using http.StatusOK. The other parameter is our response data. To return a JSON response, we are using map. We can return all sorts of data through the second parameter.

  • Logging: Things can go south anything, that's why we are making sure we are printing any errors that may occur, making things easy for debugging in future.

  • Starting the server: To Start the server, we used e.Start(). Since we were planning to start our server on port 4000. We can pass :4000 through e.Start() parameter.

Just like that, we now understand how to build an Echo server and a simple explanation of all the functions we used.

But we are not done yet..

Step 5: Now we have to test our API.

Run our go application using,

go run main.go
Enter fullscreen mode Exit fullscreen mode

If the application is running successfully, open your browser and visit http://localhost:4000/hello.

We should see json response saying hello to the entire world.

And that's it. You have successfully initialized a go module, initialized echo and created a basic performant custom api endpoint.

Thank you everyone for reading! This is my first article on dev.to. I'd love to hear your feedback, or any tips you have for a new writer. Happy coding!

Top comments (0)