Golang no required module provides package : go.mod file not found in current directory or any parent

package main
 
import (
"github.com/gin-gonic/gin"
)
 
func main() {
// Create a default routing engine
r := gin.Default()
// GET: request method; /hello: request path
// When the client requests the /hello path with the GET method, the following anonymous function will be executed
r.GET("/hello", func(c *gin.Context) {
// c.JSON: returns data in JSON format
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
// Start the HTTP service, the default is to start the service at 0.0.0.0:8080
r.Run()
}

The result is an error:

no required module provides package : go.mod file not found in current directory or any parent directory;

That is to say, the package that imports the module cannot be found

Attempt 1:

go get -u github.com/gin-gonic/gin

no effect try 2

go env -w GO111MODULE=auto

Solution

Open a terminal in the code folder where the error is reported and run

go mod init xxx

You can initialize go.mod, so run

go get -u github.com/gin-gonic/gin

Go.mod is an official package management tool newly introduced by Golang version 1.11. It is used to solve the problem that there is no place to record the specific version of the dependent package before, so as to facilitate the management of the dependent package.
Go.mod is actually a Module. The official definition of Modules is: Modules are a collection of related Go packages and a unit of source code exchange and version control. The go command directly supports working with Modules, including logging and resolving dependencies on other modules. Modules replace the old GOPATH-based method of specifying which source files to use.
Unlike traditional GOPATH, Modules does not need to contain subdirectories such as src and bin. A source code directory or even an empty directory can be used as Modules, as long as it contains the go.mod file.

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish