package main import ( "context" "fmt" "myproject/tools" "net" "net/http" "strings" "time" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) func NewEcho(ctx context.Context, restartMode *bool) *echo.Echo { timeout := 5 * time.Minute e := echo.New() e.HideBanner = true e.Server.ReadTimeout = timeout e.Server.WriteTimeout = timeout e.Server.BaseContext = func(listener net.Listener) context.Context { return ctx } e.HTTPErrorHandler = func(err error, c echo.Context) { httpError, ok := err.(*echo.HTTPError) if ok { errorCode := httpError.Code switch errorCode { case http.StatusServiceUnavailable: tools.Serve503(c) case http.StatusTooManyRequests: tools.Serve429(c) case http.StatusForbidden: tools.Serve403(c) case http.StatusUnauthorized: tools.Serve401(c) case http.StatusNotFound, http.StatusMethodNotAllowed: if strings.HasPrefix(c.Request().RequestURI, "/backend") { switch errorCode { case http.StatusNotFound: tools.Serve404(c) case http.StatusMethodNotAllowed: tools.Serve405(c) } return } c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("/?redirect=%s", c.Request().RequestURI)) default: tools.Serve500(c) } } } authStore := NewAuthStore() e.Use( middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"http://localhost:7777", "http://localhost:8808"}, AllowHeaders: []string{ echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAccessControlAllowOrigin, echo.HeaderAccessControlAllowCredentials, echo.HeaderAccessControlAllowHeaders, echo.HeaderAccessControlRequestHeaders, echo.HeaderAuthorization, }, AllowCredentials: true, }), middleware.GzipWithConfig(middleware.GzipConfig{ Level: 6, }), func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { c.Set("authStore", authStore) return next(c) } }, func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { return next(c) } }, func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { c.Set(tools.RootCtxKey, ctx) return next(c) } }, ) return e }