[Echo Framework tutorial] Example 1: Hello world

Get started with golang with a simple hello world program.

Required:

  • docker
  • docker-composer

File main:

//main.go
package main

import (
	"hello-world/handlers"

	"github.com/labstack/echo"
)

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

	// routing
	e.GET("/hello", handlers.HelloPage())
	e.GET("/api/hello", handlers.HelloAPI())

	// start the server, and log if it fails
	e.Logger.Fatal(e.Start(":8080"))
}

Handle request

//handlers/hello.go
package handlers

import (
	"net/http"

	"github.com/labstack/echo"
)

func HelloPage() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello World")
	}
}

func HelloAPI() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.JSON(http.StatusOK, map[string]interface{}{"hello": "world"})
	}
}

Access web:

API:

Source: https://github.com/nhannguyen09cntt/golang-examples/tree/master/echo/hello-world