[Echo Framework tutorial] Example 2: Routing

This is the post about handling HTTP request in Echo framework.

Create a request endpoint

Handler

#hello-world-routing\handlers\member.go
package handlers

import (
	"encoding/json"

	"github.com/labstack/echo"
)

type MemberHandler struct {
	BaseHandler
}

func NewMemberHandler() *MemberHandler {
	return &MemberHandler{}
}

func (h *MemberHandler) PostMember() echo.HandlerFunc {
	return func(c echo.Context) error {
		msg := Message{Message: "POST MEMBER"}
		c.Response().Header().Set("Server", "4Rum")
		c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
		return json.NewEncoder(c.Response()).Encode(msg)
	}
}

func (h *MemberHandler) GetMembers() echo.HandlerFunc {
	return func(c echo.Context) error {
		msg := Message{Message: "GetMembers"}
		c.Response().Header().Set("Server", "4Rum")
		c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
		return json.NewEncoder(c.Response()).Encode(msg)
	}
}

func (h *MemberHandler) GetMember() echo.HandlerFunc {
	return func(c echo.Context) error {
		id := c.Param("id")
		msg := Message{Message: "Member: " + id}
		c.Response().Header().Set("Server", "4Rum")
		c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
		return json.NewEncoder(c.Response()).Encode(msg)
	}
}

Routing

Add the new route in hello-world-routing\routers\router.go

#hello-world-routing\routers\router.go
package routers

import (
	"hello-world-routing/handlers"

	"github.com/labstack/echo"
)

func InitRoutes(e *echo.Echo) {
	v1 := e.Group("/api/v1")
	{
		v1.POST("/members", handlers.NewMemberHandler().PostMember())
		v1.GET("/members", handlers.NewMemberHandler().GetMembers())
		v1.GET("/members/:id", handlers.NewMemberHandler().GetMember())
	}
}

Init Routing

#main.go
package main

import (
	"hello-world-routing/routers"

	"github.com/labstack/echo"
)

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

	// routing
	routers.InitRoutes(e)

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

Build and run app

docker-compose up -d

Test the new endpoint using Postman

Github:

1 Like

Excusme