Echo

High performance, minimalist Go web framework

github: Echo

Features

  • Optimized HTTP router which smartly prioritize routes
  • Build robust and scalable RESTful APIs
  • Group APIs
  • Extensible middleware framework
  • Define middleware at root, group or route level
  • Data binding for JSON, XML and form payload
  • Handy functions to send variety of HTTP responses
  • Centralized HTTP error handling
  • Template rendering with any template engine
  • Define your format for the logger
  • Highly customizable
  • Automatic TLS via Let’s Encrypt
  • HTTP/2 support

Example

package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"time"

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

type LoginReq struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type response struct {
	Message string `json:"message"`
}

func main() {
	e := echo.New()
	e.Use(middleware.CORS())
	e.Use(middleware.Logger())
	e.GET("/", helloHandler)
	e.POST("/login", userLogin)
	if err := e.Start("127.0.0.1:9090"); err != nil {
		fmt.Println(err)
		return
	}
}

func helloHandler(ctx echo.Context) error {
	return ctx.String(http.StatusOK, "Hello From Echo!")
}

func userLogin(ctx echo.Context) error {
	req := &LoginReq{}
	if err := ctx.Bind(req); err != nil {
		return err
	}

	fmt.Println("user: ", req.Username, "password: ", req.Password)
	resp := response{Message: fmt.Sprintf("Hello %s", req.Username)}
	return ctx.JSON(http.StatusOK, resp)
}

requst hello handler

➜  ~ curl -X GET http://127.0.0.1:9090/
Hello From Echo!

post login

➜  ~ curl -X POST \
  http://localhost:9090/login \
  -H 'Content-Type: application/json' \
  -H 'cache-control: no-cache' \
  -d '{
        "username": "John",
        "password": "littel secret"
}'
{"message":"Hello John"}


Echo log

{"time":"2019-07-27T20:51:37.53524+08:00","id":"","remote_ip":"127.0.0.1","host":"localhost:9090","method":"POST","uri":"/login","user_agent":"curl/7.54.0","status":200,"error":"","latency":372986,"latency_human":"372.986µs","bytes_in":53,"bytes_out":25}
user:  John password:  littel secret