Home >Backend Development >Golang >Go Module Error: Why is 'package package1 is not in GOROOT' and how do I fix it?

Go Module Error: Why is 'package package1 is not in GOROOT' and how do I fix it?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 08:07:11875browse

Go Module Error: Why is

Go Module Error: Package Not in GOROOT

Issue:

When running go run main.go, users encounter the following error:

package package1 is not in GOROOT (/usr/local/go/src/package1)

Cause:

This error occurs when the Go module system cannot locate the specified package in the GOROOT directory.

Solution:

To resolve this issue, ensure that the environment variables are properly configured. The following steps should be followed:

  1. Configure GOPATH:

    • Create a GOPATH directory outside of GOROOT, such as /mnt/sda1/programming/gopath.
    • Set the GOPATH environment variable to point to this directory:

      export GOPATH=/mnt/sda1/programming/gopath
  2. Adjust GOROOT:

    • Ensure that GOROOT is set to the system-installed Go root directory:

      export GOROOT=/usr/local/go
  3. Add GOROOT to PATH:

    • Add GOROOT to the PATH environment variable:

      export PATH=$PATH:$GOROOT/bin
  4. Enable Go Modules:

    • Set the GO111MODULE environment variable to on:

      export GO111MODULE=on
  5. Update Bashrc:

    • Add the above environment variables to the .bashrc file.
    • Load the .bashrc file in the terminal:

      source ~/.bashrc
  6. Reinitialize Module:

    • Navigate to the main folder containing main.go.
    • Reinitialize the Go module with go mod init main.
  7. Create Package Directory:

    • Create a directory for the package, e.g., package1.
    • Inside package1, create the necessary files with the package package1 directive.
    • Do not create a go.mod file within the package directory.
  8. Import Package:

    • In main.go, import the package:

      import "main/package1"
  9. Load bashrc again:

    • run source ~/.bashrc again to make sure updated setting applied.

Once these steps are complete, the package package1 is not in GOROOT error should be resolved, and the main.go file should run successfully.

The above is the detailed content of Go Module Error: Why is 'package package1 is not in GOROOT' and how do I fix it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn