Labstack/echo

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

Install Dependencies

From the root directory of your module, execute:

go get github.com/labstack/echo/v4@v4.11.4

Server

package main

import (
	"net/http"

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

func hello(c echo.Context) error {
	return c.String(http.StatusOK, "hello!")
}

func main() {
	s := echo.New()
	// Middleware
	s.Use(middleware.Logger())
	s.Use(middleware.Recover())
	// Routes
	s.GET("/", hello)
	// Start server
	s.Logger.Fatal(s.Start(":30000"))
}

Registering Handlers Generated by oapi-codegen from an OpenAPI Specification

oapi-codegen Server Code Generation

oapi-codegen generates a ServerInterface interface that exposes methods for each path/operation pair specified in the OpenAPI specification:

// ServerInterface represents all server handlers.
type ServerInterface interface {
  // (GET /pets)
  GetPets(ctx echo.Context, params GetPetsParams) error
  // (POST /pets)
  CreatePet(ctx echo.Context) error
  ...
}

Implement the ServerInterface:

type PetStoreServer struct {
}

func NewPetStoreServer() *PetStoreServer {
	return &PetStoreServer{}
}

func (s *PetStoreServer) GetPets(ctx echo.Context, params petstore.GetPetsParams) error {
  ...
}

func (s *PetStoreServer) CreatePet(ctx echo.Context) error {
  ...
}

...

Then instantiate an echo server and register the handlers:

s := NewPetStoreServer()
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Routes
petstore.RegisterHandlers(e, s)

// Start server
e.Logger.Fatal(e.Start(":30000"))

For details on how to declare and implement various HTTP operations, see:

OpenAPI Specification Path Examples

Programming Model

Figuring Out Whether the Server Has Started

Stopping the Server

https://echo.labstack.com/docs/cookbook/graceful-shutdown

Retrieving Data

https://echo.labstack.com/docs/request