php editor Xinyi is here to introduce to you a common problem in GoLang: custom package import problem. In Go language development, we often need to use custom packages to implement some specific functions. However, when importing custom packages, some problems sometimes occur, such as package cannot be found, package name conflicts, etc. This article will answer these questions in detail and provide solutions to help developers better handle custom package import problems and improve development efficiency.
I am learning golang and encountered a problem.
I used go mod init main
to create the mod file
Next I created the controller and routing folders as shown 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 this
Module main
Now when I try to import the controller into the router it gives me an import error.
I have been doing the following. Try - 1
import ( "$gopath/controllers" "github.com/gin-gonic/gin" )
It gives invalid import path: "$gopath/controllers" syntax
error
Try - 2
import ( "$gopath/main/controllers" "github.com/gin-gonic/gin" )
Same error
Try - 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()); }
Throws this error, Unable to import main/controllers (no required module provides package "main/controllers")
I've been stuck with this issue for 3-4 hours, can someone please suggest me how to import this controller into my routes.
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 directory contollers
to controllers
to match the package name (missing r
).
Delete the vendor
folder.
illustrate:
main
has a special meaning in go. Quoted from golang specification:A complete program is created by transitively linking a single unimported package named main package with all its imported packages. The main package must have the package name main and declare a function main that takes no parameters and returns no value.
The above is the detailed content of GoLang custom package import problem. For more information, please follow other related articles on the PHP Chinese website!