echo icon indicating copy to clipboard operation
echo copied to clipboard

Proposal: Application state

Open behnambm opened this issue 6 months ago • 5 comments

Application state

This proposal seeks to introduce an Application State Management feature in Echo. This feature will enable the ability to access a store application wide. Mmiddlewares and request handlers will be able to access this store because they both have access to Echo struct. The state's data will not change from request to request.

Similar functionality is available in other frameworks, such as FastAPI.

API

Set(key string, val any) Get(key string) (any, bool)

We need to discuss about some cases that needs to be considered in the API design. For example, should we override the already existing data? Or return an error?

Sample

package main

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"net/http"
)

func main() {
	e := echo.New()

	testClient := http.Client{}
	testClient.Timeout = 42
	e.State.Set("myClient", &testClient)

	e.GET("/", hello)

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

func hello(c echo.Context) error {
	client, ok := c.Echo().State.Get("myClient")
	httpClient, ok := client.(*http.Client)
	if ok {
		fmt.Println("Timeout :", httpClient.Timeout)
	}

	return c.String(http.StatusOK, "Hello, World!")
}

behnambm avatar Aug 07 '24 14:08 behnambm