Home > Backend Development > Golang > How to Fix the 'Package Not in GOROOT' Error When Using Go Modules?

How to Fix the 'Package Not in GOROOT' Error When Using Go Modules?

DDD
Release: 2024-12-10 20:12:11
Original
262 people have browsed it

How to Fix the

Resolving "Package Not in GOROOT" Error for Go Modules

A common issue encountered when working with Go modules is receiving the error message "package [package name] is not in GOROOT." This error is generally caused by improper configuration of environment variables.

Solution

To resolve this error, ensure that the following environment variables are correctly set:

  • GO111MODULE: Set to "on" to enable modules support.
  • GOPATH: The path to a workspace directory for modules, which should be outside the GOROOT directory.
  • GOROOT: The installation location of the Go SDK.
  • PATH: Include $GOPATH/bin and $GOROOT/bin in the path.

Configuration in Bash

In the .bashrc file, add the following lines:

export GO111MODULE=on
export GOPATH=/path/to/workspace
export PATH=$PATH:$GOPATH/bin:$GOROOT/bin
export GOROOT=/path/to/GOROOT
Copy after login

After Configuration

After setting the environment variables, source the .bashrc file to load the changes.

source ~/.bashrc
Copy after login

Go Module Workflow

To use Go modules, follow these steps:

  1. Create a new main project directory.
  2. Inside the main directory, run go mod init main.
  3. Create a subdirectory for the new package, e.g., package1.
  4. Within package1, create files with the package package1 header but omit the go.mod file.
  5. In main.go, import and use the package from main/package1.

By following these steps and ensuring proper environment configuration, the "package not in GOROOT" error can be resolved.

The above is the detailed content of How to Fix the 'Package Not in GOROOT' Error When Using Go Modules?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template