Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
Matthias
@matthias:bsr.mn
[m]

question. I am trying to add a custom middleware which changes both method and path (I know there are existing middlewares for both and I checked their source)

        req := c.Request()
        req.Method = "PUT"
        path := req.URL.Path
        url, _ := req.URL.Parse(path + "/9")
        req.URL = url

This succeeds in changing the method, but it fails changing the path, any idea what's up with that?

Matthias
@matthias:bsr.mn
[m]
just to be clear, I am using my middleware with e.Preas recommended
Matthias
@matthias:bsr.mn
[m]
Nevermind. Worked around it another way
Martti T.
@aldas
@matthias:bsr.mn could you explain your (business) use-case (why/when) for changing method/path?
1 reply
Matthias
@matthias:bsr.mn
[m]
i mean the proxy middleware works just fine for websockets, but not while proxying unix sockets haha
Yagyesh Srivastava
@T0D0-FIXME

I am facing the "No token found " when I try to use echo framework for expositioning my metrics and using prometheus to scrape them.
While instrumenting my labstack echo web server with prometheus, I followed the example here: https://echo.labstack.com/middleware/prometheus/
and didnt instrument any custom metrics yet, still not able to get it to work with prometheus scraper with just the basic echo framework metrics. Following is the scrape config that I used:

- job_name: 'nebula-staging'
  static_configs:
  - targets: ['10.X.Y.Z:8000']
    labels: 
      instance: 'nebula'

Also, I am able to curl to this address and get the metrics, when I use promtool to check the metrics for any inconsistency I dont find any. Not too sure what to do, does anyone have any clue? Would be of great help, thanks!

Nino
@ninom4ster:matrix.org
[m]
Hello! I was wondering if Echo supports adding/removing routes while it's running or do I have to restart it?
1 reply
Nino
@ninom4ster:matrix.org
[m]
alright. thanks!
Tornike Razmadze
@torniker

Hi, I have been stuck trying to configure my echo app to serve with https, but have no success. I've read and tried this: https://echo.labstack.com/cookbook/auto-tls ..

So at this point i am getting following error:
echo: http: TLS handshake error from {some-ip}:27002: acme/autocert: unable to satisfy "https://acme-v02.api.letsencrypt.org/acme/authz-v3/53188301650" for domain "mydomain.com": no viable challenge type found

2 replies
Thomas Elsgaard
@elsgaard
Hi everybody! I am serving index.html which loads css, js etc.by using e.Static("/dashboard", "/web"), BUT i would like to retrieve the query params. How can i achieve this? How do i call a normal handler like e.GET and get the query params, and then return either the path to /web or the specific index.html file ?
jahidmixmaster
@jahidmixmaster
Hi everybody, I saw a CRUD example here (https://echo.labstack.com/cookbook/crud/). My question is Variable Users and Seq both are not Go routine safe (thread-safe). Two Goroutines can access both Variables at the same time.
Martti T.
@aldas
these variables are not thread safe. maybe for shorter example sync.mutex is left out. anyway - in real world you would use some proper storage engine and their locking mechanisms
jahidmixmaster
@jahidmixmaster
Thank you so much.
porty
@tqrj
hello
Parsing JSON request data appears not to be supported´╝č
I have to parse it manually
image.png
Martti T.
@aldas
porty
@tqrj
ok thank
danvenn
@danvenn
Hey all
I'd like to create a test that I can hand a path to and echo will route for me and send it to the appropriate handler
Has anyone here done that before? So far I can only find documentation for manually giving it a specific handler function
This message was deleted
Something like this doesn't seem to return anything
func GETTER(path string, params []string, paramValues []string) string {
    e := echo.New()
    req := httptest.NewRequest(http.MethodGet, path, nil)
    rec := httptest.NewRecorder()

    c := e.NewContext(req, rec)

    c.SetParamNames(params...)

    //res := rec.Result()
    defer rec.Result().Body.Close()
    c.SetParamValues(ClientIdString)

    //controllers.GetFullProfile(c)
    return rec.Body.String()
}
1 reply
kyoukhana
@kyoukhana
is there a good Guide to get started with Echo??
1 reply
Emil Nikolov
@e-nikolov
Is there a way to enumerate all routes of an echo router? Something similar to chi.Walk() - https://github.com/go-chi/chi/blob/d32a83448b5f43e42bc96487c6b0b3667a92a2e4/tree.go#L827
Martti T.
@aldas
e.Routes() gives you all registered routes (with default router). does not include vhost ones
Preetham
@preethamsathyamurthy
Hi, how to pass the echo logging middleware that can be used by other packages, when we write the application ?
Martti T.
@aldas
johndiego
@johndiego
how i can testing my routes?
func login(c echo.Context) error {
    validate := validator.New()
    u := new(Auth)
    if err := c.Bind(u); err != nil {
        return echo.NewHTTPError(http.StatusBadRequest)
    }
    err := validate.Struct(u)

    if err != nil {
        return echo.NewHTTPError(http.StatusBadRequest)
    }
    user , err := domain.GetAuthByUsername(u.Username,u.Password)

    if user.Id == 0  {
          return echo.ErrUnauthorized
    }
    claims := &jwtCustomClaims{ user.Username,*user.Active,*user.Admin,user.Roles,
        jwt.StandardClaims{
            ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
        },
    }
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

    t, err := token.SignedString([]byte(os.Getenv("ACCESS_SECRET")))
    if err != nil {
        return err
    }

    return c.JSON(http.StatusOK, echo.Map{
        "token": t,"roles":user.Roles,"username": user.Username,
    })
}
func startAuthRouters(app *echo.Echo){
    auth := app.Group("/auth/login")
    auth.POST("", login)
}
MY TESTS
package controllers

import (
    "testing"
    "net/http"
    "net/http/httptest"
    "github.com/labstack/echo/v4"
    "github.com/stretchr/testify/assert"
    "fmt"
)

func TestAuth(t *testing.T) {
    // t.Parallel()
    // Start()
    t.Run("Controllers ECHO", func(t *testing.T) {

        req := httptest.NewRequest(echo.POST, "/auth/login",nil)
        rec := httptest.NewRecorder()

        // // req.Header.Set("Content-Type", "application/json")
        fmt.Println(req)
        fmt.Println(rec)
        // // req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
        // c.SetPath("/auth/login")
        // h := login(c)
        // fmt.Println(h)
        // fmt.Println(rec)
        // assert.Equal(t, http.StatusBadRequest, rec.Code)
        assert.Equal(t, http.StatusBadRequest, rec.Code)

    })
}
image.png
Martti T.
@aldas
func TestHandler(t *testing.T) {
    e := echo.New()
    req := httptest.NewRequest(http.MethodGet, "/", nil)
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)

    handler := func(c echo.Context) error {
        return c.String(http.StatusOK, "OK")
    }

    err := handler(c)

    assert.NoError(t, err)
    assert.Equal(t, http.StatusOK, rec.Code)
}
Martti T.
@aldas

lets say your code is

type authService interface {
    GetAuthByUsername(username string, password string) (string, error)
}
type AuthRoutes struct {
    auth authService
}

func (a AuthRoutes) login(c echo.Context) error {
    auth, err := a.auth.GetAuthByUsername("user", "pass")
    if err != nil {
        return err
    }
    return c.JSON(http.StatusCreated, map[string]string{"auth": auth})
}

then you would create something like that for test

type authServiceMock struct {
    mock.Mock
}

func (m *authServiceMock) GetAuthByUsername(username string, password string) (string, error) {
    args := m.Called(username, password)
    return args.String(0), args.Error(1)
}

func TestHandler(t *testing.T) {
    e := echo.New()
    req := httptest.NewRequest(http.MethodGet, "/", nil)
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)

    serviceMock := new(authServiceMock)
    serviceMock.On("GetAuthByUsername", "user", "pass").Return("myauth", nil)
    auth := AuthRoutes{auth: serviceMock}

    err := auth.login(c)

    assert.NoError(t, err)
    assert.Equal(t, http.StatusCreated, rec.Code)

    serviceMock.AssertExpectations(t)
}

in that way you can mock that auth service inside your handler

mock.mock is from testify "github.com/stretchr/testify/mock"
Matthias
@matthias:bsr.mn
[m]

hi guys. I am using the proxy module and am proxying some "blocking requests" meaning requests that live for 5 minutes. my clients (that are connecting to the echo proxy) are killing them if they don't need them anymore, but on the echo proxy side, those requests seem to stay open. is that a bug, or expected behaviour?

how can I make sure that those cancelled requests are properly cleaned up?

Matthias
@matthias:bsr.mn
[m]
ah wait, I think there might be something seriously wrong with my code...
ok yeah I was using ModifyResopnse and I didn't close the response.body, which caused the issue
sorry for the noise!
Martti T.
@aldas
It is probably better to ask questions in https://github.com/labstack/echo/discussions I do not think there are many people actively monitoring this chat.
Matthias
@matthias:bsr.mn
[m]
is there any way to use the proxy middleware dynamically? say i have the route /proxy/server1/foo I want to proxy http://server1/foo and if I have /proxy/server2/foo I want to proxy http://server2/foo. server1 and server2 can be anything in this scenario
Matthias
@matthias:bsr.mn
[m]
nevermind, figured it out