Labstack/echo: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 52: Line 52:
type PetStoreServer struct {
type PetStoreServer struct {
   // ...
   // ...
}
func NewPetStoreServer() *PetStoreServer {
return &PetStoreServer{}
}
}



Revision as of 20:57, 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

Implement oapi-codegen-generated ServerInterface

oapi-codegen generates a ServerInterface interface that exposes methods to be implemented by the server.

Implement that interface:

type PetStoreServer struct {
  // ...
}

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

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

Register the Handlers

var server = NewPetStoreServer()
e := echo.New()
petstore.RegisterHandlers(e, server)