Home > Enterprise >  How do I connect a function from another directory to Go/Echo?
How do I connect a function from another directory to Go/Echo?

Time:08-21

Created a project with structure:

lolo
--views
----count_private.go
--go.mod
--go.sum
--logs.log
--main.go

Code in main.go

package main

import(
"lolo/views"

"github.com/labstack/echo/v4"
)

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

e.GET("/f_count_private", views.F_count_private)

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

Code in count_private.go

package views

import(
"net/http"

"github.com/labstack/echo"
)

func F_count_private(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}

When running the code via the $ go run main.go command, an error is thrown:

# lolo/views
views\count_private.go:9:6: F_count_private redeclared in this block
        views\cat.go:7:6: other declaration of F_count_private

Can you please tell me how to get around the error and make it so that I can use the f_count_private(...) function from another file in main()?

CodePudding user response:

In the views package you import the "github.com/labstack/echo/v4" package.

In main you use e.GET from github.com/labstack/echo/v4, and in the views package you import "github.com/labstack/echo"

These are different packages for go, so the echo.Context type in the FCountPrivate definition is different from the Context type used in the HandlerFunc type from the github.com/labstack/echo/v4 package.

Response @user:371023

  • Related