Overcoming Local Package Import Headaches in Go
When working with Go codebases, importing packages from other directories within the same project can be a bit tricky. If you've encountered errors similar to those described in the question, such as "local import in non-local package" or "cannot find package in $GOROOT or $GOPATH," here's the solution to fix it.
Go uses a specific path to search for imported packages, which starts at $HOME/go/src. To import packages from local directories, it's crucial to adjust the import statement accordingly. In this case, since the common and routers packages are located in /home/me/go/src/myapp, the correct import statement is:
import ( "log" "net/http" "myapp/common" "myapp/routers" )
By prepending "myapp" to the package names, you're instructing Go to search within the designated project directory. This method ensures that the local packages are successfully imported, resolving the errors you were encountering.
The above is the detailed content of How Do I Correctly Import Local Packages in Go?. For more information, please follow other related articles on the PHP Chinese website!