Home >Backend Development >Golang >How Can I Correctly Import Local Packages in Go Using Relative Paths?
When localizing code packages in Go, importing them can be a challenge. This question explores an issue where a developer encounters errors while trying to import local packages using relative paths.
In the example provided, the developer attempted to import local packages common and routers from the /home/me/go/src/myapp directory using relative import statements. However, these imports failed with errors indicating that local imports are not allowed in non-local packages.
Additionally, when using package names without the relative paths, the compiler reported that the packages could not be found.
The solution lies in understanding the Go import path. By default, Go starts its import search path from $HOME/go/src. This means that the packages must be located directly under this directory or within subdirectories.
In this case, the local packages common and routers are not placed directly under $HOME/go/src. To resolve the import issue, the developer needs to prepend the project name myapp to the package import paths.
Therefore, the correct import statements should be:
import ( "log" "net/http" "myapp/common" "myapp/routers" )
With this modification, the Go import path will correctly resolve to the local packages and eliminate the errors.
The above is the detailed content of How Can I Correctly Import Local Packages in Go Using Relative Paths?. For more information, please follow other related articles on the PHP Chinese website!