In my Go project, I want to break out some generic functionality into a Go module, separate from the main project. I'm doing this outside of GOPATH in keeping with go's future. I don't want to publish the module on GitHub or anywhere else.
All my attempts to import this module into the main project result in:
cannot find module for path X
I've run go mod init X
in the module's folder. The contents of its go.mod
file is:
module X
Building or installing this module seems to do nothing. I've found no sign of it in $GOPATH/pgk/mod
.
I've tried a variety of import statements:
import "X"
import "../x"
(relative path to the module directory)import "../x/X"
(path to the directory + module name)
Help!
So you wrote a Go "library" module which:
- you don't want to publish on GitHub or elsewhere
- you want to import and use it in your project (the "main" module).
Use the
replace
directive to solve this problem.
Given the module name "X" as you've called it, in your main module add the following lines:
require "X" v0.0.0
replace "X" v0.0.0 => "{local path to the X module}"
The path should point to the root directory of the module, and can be absolute or relative.
To import package util from module X:
import "X/util"
(You don't import modules. You import packages from modules.)
Explanation
Go's module functionality is designed for publicly published modules. Normally, a module's name is both its unique identifier and the path to its public repo. When your go.mod declares a module dependency with the require
directive, Go will automatically find and retrieve the specified version of the module at that path.
(See also in the Go Modules FAQ, Can I work entirely outside of VCS on my local filesystem?)
If, for example, your go.mod
file contains require github.com/some/dependency v1.2.3
, Go will retrieve the module from GitHub at that path. But if it contains require X v0.0.0
, "X" isn't an actual path and you will get the error cannot find module for path X
.
The replace
directive allows you to specify a replacement path for a given module identifier and version. There are many reasons you'd want to do this, such as to test changes to a module before pushing them to the public repo. But you can also use it to bind a module identifier to local code you don't ever intend to publish.
Hope this helps.
来源:https://stackoverflow.com/questions/52123627/how-do-i-resolve-cannot-find-module-for-path-x-importing-a-local-go-module