Skip to main content

Echo Hello World

Welcome to your first step in learning the Echo framework! In this tutorial, you'll create a simple "Hello World" web server using Echo. This introduction will give you a solid foundation for building more complex web applications with Echo in the future.

What is Echo?

Echo is a high-performance, extensible, minimalist web framework for Go (Golang). It's designed to make it easy to build web applications and APIs with minimal effort while providing robust features.

Prerequisites

Before we begin, ensure you have:

  • Go installed on your system (version 1.14 or later recommended)
  • Basic knowledge of Go programming
  • A code editor of your choice

Setting Up Your First Echo Project

Let's start by creating a new directory for our project and initializing a Go module:

bash
mkdir echo-hello-world
cd echo-hello-world
go mod init echo-hello-world

Next, we need to install the Echo framework:

bash
go get github.com/labstack/echo/v4

Creating Your First Echo Application

Now, let's create a file named main.go with the following content:

go
package main

import (
"net/http"

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

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

// Define a route handler
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})

// Start the server
e.Logger.Fatal(e.Start(":8080"))
}

Understanding the Code

Let's break down what this code does:

  1. Importing Packages:

    go
    import (
    "net/http"

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

    We import the Echo framework and the standard HTTP package for status codes.

  2. Creating an Echo Instance:

    go
    e := echo.New()

    This creates a new instance of Echo which will be our web server.

  3. Defining a Route:

    go
    e.GET("/", func(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
    })

    This sets up a route handler for HTTP GET requests to the root path (/). When someone visits this URL, Echo will respond with the string "Hello, World!" and a 200 OK status code.

  4. Starting the Server:

    go
    e.Logger.Fatal(e.Start(":8080"))

    This starts the server on port 8080 and logs any fatal errors.

Running Your Application

To run your application, execute the following command in your terminal:

bash
go run main.go

You should see output similar to this:

   ____    __
/ __/___/ / ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.x.x
High performance, minimalist Go web framework
https://echo.labstack.com
⇨ http server started on [::]:8080

Now, open your web browser and navigate to http://localhost:8080. You should see the text "Hello, World!" displayed.

Testing Your API with curl

You can also test your API using curl from the command line:

bash
curl http://localhost:8080

Output:

Hello, World!

Adding More Routes

Let's extend our application to include more routes:

go
package main

import (
"net/http"

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

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

// Define route handlers
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})

e.GET("/hello/:name", func(c echo.Context) error {
// Extract the name parameter from the request
name := c.Param("name")
return c.String(http.StatusOK, "Hello, " + name + "!")
})

e.GET("/greet", func(c echo.Context) error {
// Get the name from query parameter
name := c.QueryParam("name")
if name == "" {
name = "Guest"
}
return c.String(http.StatusOK, "Greetings, " + name + "!")
})

// Start the server
e.Logger.Fatal(e.Start(":8080"))
}

Now our application has three routes:

  1. GET / - Returns "Hello, World!"
  2. GET /hello/:name - Returns a personalized greeting using a path parameter
  3. GET /greet?name=YourName - Returns a greeting using a query parameter

Try these URLs in your browser:

  • http://localhost:8080/hello/John
  • http://localhost:8080/greet?name=Jane

Real-World Application: JSON Response

Most web applications return data in JSON format. Let's modify our application to return a JSON response:

go
package main

import (
"net/http"
"time"

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

// Message represents a response structure
type Message struct {
Content string `json:"content"`
Timestamp time.Time `json:"timestamp"`
}

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

// JSON response example
e.GET("/api/message", func(c echo.Context) error {
message := &Message{
Content: "Hello, World!",
Timestamp: time.Now(),
}
return c.JSON(http.StatusOK, message)
})

// Start the server
e.Logger.Fatal(e.Start(":8080"))
}

When you visit http://localhost:8080/api/message, you'll receive a JSON response like:

json
{
"content": "Hello, World!",
"timestamp": "2023-08-28T15:30:45.123Z"
}

Summary

Congratulations! You've created your first Echo application. In this tutorial, you learned:

  • How to set up an Echo project
  • Creating a basic web server
  • Adding route handlers
  • Working with path and query parameters
  • Returning different types of responses (string and JSON)

This foundation will help you build more complex web applications as you continue learning the Echo framework.

Additional Resources

Exercises

To reinforce your learning, try these exercises:

  1. Create a new route that returns HTML content instead of plain text.
  2. Add a POST route that accepts JSON data and returns it back to the client.
  3. Implement a route that returns different status codes based on a query parameter.
  4. Create a route that serves a static file (like an image or CSS file).
  5. Implement a simple API that performs a basic calculation based on query parameters.

Keep experimenting with Echo to discover its powerful features and simplicity!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)