I'm learning GoLang, and got into an issue.
I created the mod file with go mod init main
Next I created controller and Routes folder which looks something like below:
├── contollers
│ └── users.controller.go
├── routes
│ ├── index.go
│ └── users.routes.go
├── vendor
│ └── modules.txt
├── go.mod
├── go.sum
└── main.go
in the mod file the module looks like something like this
module main
Now when I'm trying to import controller into router, it's giving me import error.
I been doing below things. Attempt - 1
import (
"$GOPATH/controllers"
"github.com/gin-gonic/gin"
)
it's giving invalid import path: "$GOPATH/controllers"syntax
error
Attempt - 2
import (
"$GOPATH/main/controllers"
"github.com/gin-gonic/gin"
)
again the error is same
Attempt - 3
import (
"main/controllers"
"github.com/gin-gonic/gin"
)
controller.go
package controllers;
import (
"fmt"
"github.com/gin-gonic/gin"
)
func HealthCheck() gin.HandlerFunc {
return func (c *gin.Context) {
fmt.Println("reached controller")
}
}
router.go
package routes
import (
"bootcamp.com/server/controllers"
"github.com/gin-gonic/gin"
)
func UserRouters(inComingRoutes *gin.Engine) {
inComingRoutes.GET("/api/health", controllers.HealthCheck());
}
it's throwing error like this, could not import main/controllers (no required module provides package "main/controllers")
I been stuck with this for 3-4 hours, can anyone please suggest me how can I import that controller into my route.
Thanks in advance.
go.mod
:- module main
+ module example.com/hello
import (
- "main/controllers"
+ "example.com/hello/controllers"
"github.com/gin-gonic/gin"
)
controller.go
(remove trailing ;
):- package controllers;
+ package controllers
rename the directory contollers
to controllers
to match the package name (r
is missed).
remove the vendor
folder.
Explanation:
main
has a special meaning in go. Quotes from the golang spec:A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.