Перейти к основному содержимому

Первая программа на Echo

Разработчику Архитектору

Первая программа на Echo

Echo — зрелый фреймворк поверх net/http: реализует http.Handler, гибкий middleware, валидация.

Обзор: Фреймворки Go · Gin · Fiber · Тестирование.


Инициализация

mkdir echo-notes && cd echo-notes
go mod init example.com/echo-notes
go get github.com/labstack/echo/v4

REST API «Заметки»

main.go:

package main

import (
"net/http"
"strconv"
"sync"

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

type Note struct {
ID int `json:"id"`
Text string `json:"text"`
}

type NoteCreate struct {
Text string `json:"text" validate:"required,min=1,max=500"`
}

var (
notes []Note
nextID = 1
mu sync.Mutex
)

func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())

e.GET("/health", func(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
})

g := e.Group("/api")
g.GET("/notes", listNotes)
g.POST("/notes", createNote)
g.DELETE("/notes/:id", deleteNote)

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

func listNotes(c echo.Context) error {
mu.Lock()
defer mu.Unlock()
return c.JSON(http.StatusOK, notes)
}

func createNote(c echo.Context) error {
var body NoteCreate
if err := c.Bind(&body); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
mu.Lock()
note := Note{ID: nextID, Text: body.Text}
nextID++
notes = append(notes, note)
mu.Unlock()
return c.JSON(http.StatusCreated, note)
}

func deleteNote(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid id")
}
mu.Lock()
defer mu.Unlock()
for i, n := range notes {
if n.ID == id {
notes = append(notes[:i], notes[i+1:]...)
return c.NoContent(http.StatusNoContent)
}
}
return echo.NewHTTPError(http.StatusNotFound, "not found")
}
go run .

Проверка

curl http://127.0.0.1:8080/health
curl http://127.0.0.1:8080/api/notes
curl -X POST http://127.0.0.1:8080/api/notes \
-H "Content-Type: application/json" \
-d '{"text":"Изучить Echo"}'

Отличия от Gin

EchoGin
Совместимостьполный http.Handlerсвой контекст
Валидацияvalidator через middlewarebinding теги
Стиль APIближе к идиоматичному Goвыше throughput в бенчмарках

Дальше


См. также

Другие статьи этого же раздела в боковом меню (как на странице «О разделе»).