Go framework Echo middleware usage

155 views Asked by At

In my main function I have used the go framework echo to create a Logger and Recover

func main() {

    db := initDB("storage.db")
    migrate(db)

    e := echo.New()

    -> e.Use(middleware.Logger())
    -> e.Use(middleware.Recover())

    e.File("/", "public/index.html")
    e.GET("/tasks", handlers.GetTasks(db))
    e.PUT("/tasks", handlers.PutTask(db))
    e.DELETE("/tasks/:id", handlers.DeleteTask(db))

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

However 2 errors have shown stating:

cannot use middleware.Recover() (value of type "github.com/labstack/echo".MiddlewareFunc) as "github.com/labstack/echo/v4".MiddlewareFunc value in argument to e.Use

the same with the logger.

I have tried removing and reinstalling echo via go get ... and re-configuring go.mod file, but the error remains.

import (
    "database/sql"

    "github.com/Alfred-Jijo/go-vue-echo/handlers"
    "github.com/labstack/echo/middleware"
    "github.com/labstack/echo/v4"

    _ "github.com/mattn/go-sqlite3"
)

My imports haven't changed since basically the start. I suspect my go.mod file has an error in it but I'm too new to understand it.

require github.com/labstack/echo/v4 v4.11.3

require (
    github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
    github.com/labstack/echo v3.3.10+incompatible
    github.com/labstack/gommon v0.4.1 // indirect
    github.com/mattn/go-colorable v0.1.13 // indirect
    github.com/mattn/go-isatty v0.0.20 // indirect
    github.com/mattn/go-sqlite3 v1.14.18
    github.com/valyala/bytebufferpool v1.0.0 // indirect
    github.com/valyala/fasttemplate v1.2.2 // indirect
    golang.org/x/crypto v0.15.0 // indirect
    golang.org/x/net v0.17.0 // indirect
    golang.org/x/sys v0.14.0 // indirect
    golang.org/x/text v0.14.0 // indirect
)

I've also tried literally building the project again but the same error persists.

1

There are 1 answers

0
Zeke Lu On BEST ANSWER

The error message is clear. The following types are two different types:

  • "github.com/labstack/echo".MiddlewareFunc
  • "github.com/labstack/echo/v4".MiddlewareFunc

Looks like that you're using echo v4, then the import path for the middleware should be github.com/labstack/echo/v4/middleware.

Follow these steps to fix the issue:

  1. replace the import path
    "github.com/labstack/echo/middleware"
    
    with
    "github.com/labstack/echo/v4/middleware"
    
  2. then run
    go mod tidy