Labstack/echo: Difference between revisions
Jump to navigation
Jump to search
Line 92: | Line 92: | ||
For details on how to declare and implement various HTTP operations, see: {{Internal|OpenAPI_Specification_Path#Examples|OpenAPI Specification Path Examples}} | For details on how to declare and implement various HTTP operations, see: {{Internal|OpenAPI_Specification_Path#Examples|OpenAPI Specification Path Examples}} | ||
=Programming Model= | |||
==Retrieving Data== | |||
{{External|https://echo.labstack.com/docs/request}} |
Revision as of 22:44, 26 January 2024
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
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: