Package is not in goroot ошибка

In newer versions (post 1.13) of Go, you don’t need to set environment variables like GOPATH, GOBIN, etc.

You also need to have a go.mod file at the project root. This will make the directory a Go module. This is also where the .git/ is located. This means that only one go.mod is needed per repository. Inside the project root you could do a go mod init remote-repo.com/username/repository

I installed Go using Homebrew on macOS so GOROOT is /opt/homebrew/Cellar/go/1.17.5/libexec. This location contains the standard library and runtimes for Go.

test and run commands are run in the format go COMMAND package_path/xxx. Without specifying the package_path ./ and just running go COMMAND xxx, the compiler assumes that the module xxx is located in GOROOT, and throws error package xxx is not in GOROOT (path/to/GOROOT/src/xxx) because it doesn’t exist.

This behavior is expected because the package we are working with is not part of the Go SDK, i.e., not in GOROOT. The package we are working with will either end up in the go workspace or in the current working directory. Running go install compiles and puts an executable binary in $GOBIN (a.k.a $GOPATH/bin — here $GOPATH is the Go workspace). Running go build from inside a package compiles and puts an execuatble in that directory.

You haven’t listed the files inside the server/ package and which file has the main function, so I’ll emulate 3 workflows of a calculator each demonstrating more complexity. The last workflow is similar to your directory structure.

Directory Structure

Version 1:

  • Getting started with packages

  • Basic functionality

calculatorv1
├── go.mod                      <- go mod init github.com/yourname/calculatorv1
└── basic/
    ├── add.go
    ├── add_test.go
    ├── main.go
    ├── multiply.go
    └── multiply_test.go

Version 2:

  • More functionality

  • Multiple packages

calculatorv2
├── go.mod                      <- go mod init github.com/yourname/calculatorv2
├── main.go
└── basic/
│   ├── add.go
│   ├── add_test.go
│   ├── multiply.go
│   └── multiply_test.go
└─── advanced/
     ├── square.go
     └── square_test.go

Version 3:

  • Even more functionality

  • Nested packages

calculatorv3
├── go.mod                      <- go mod init github.com/yourname/calculatorv3
├── main.go
└── basic/
│   ├── add.go
│   ├── add_test.go
│   ├── multiply.go
│   └── multiply_test.go
└─── advanced/
     ├── square.go
     ├── square_test.go
     └── scientific/
         ├── declog.go
         └── declog_test.go

Workflow

Note: Substitute xxx with basic, advanced, or advanced/scientific depending on the version you’re working with.

  • Initialize Go module in the project directory (one of calculatorv1, calculatorv2, or calculatorv3) using go mod init

  • Run tests

    go test -v ./... (from the project root, recursively execute all test suites)

    OR

    go test -v ./xxx (from the project root, run the test suite in package «xxx»)

    OR

    cd xxx/
    go test -v            # (from inside the package)
    
  • Compile and execute package

    go run ./... (from the project root, recursively run all .go files except tests)

    OR

    go run ./xxx (from the project root, run all .go files in «xxx» package except tests)

    OR

    cd xxx
    go run .              # (from inside the package)
    

    NOTE: Only files in the main package are executable, i.e., files having declaration package main. This means that go run ./xxx will only work with version1, and not versions 2 and 3. So instead for versions 2 and 3, run go run main.go


Code

Very easy to fill in incomplete bits

Version 1

add.go

package main

func addition(x int, y int) int {
    return x + y
}

add_test.go

package main

import "testing"

func TestAdd(t *testing.T) {

    t.Run("adding two positive numbers", func(t *testing.T) {
        sum := addition(2, 2)
        expected := 4
        
        if sum != expected {
            t.Errorf("Expected %d; but got %d", expected, sum)
        }
    })
    
    t.Run("adding two negative numbers", func(t *testing.T) {
        sum := addition(-3, -4)
        expected := -7

        if sum != expected {
            t.Errorf("Expected %d; but got %d", expected, sum)
        }
    })

    t.Run("adding one positive and one negative integer", func(t *testing.T) {
        sum := addition(1, -3)
        expected := -2

        if sum != expected {
            t.Errorf("Expected %d; but got %d", expected, sum)
        }
    })
    
}

main.go

package main

import "fmt"

func main() {
    var num1 int = 1
    var num2 int = 2
    
    sum := addition(num1, num2)
    product := multiplication(num1, num2)

    fmt.Printf("The sum of %d and %d is %dn", num1, num2, sum)
    fmt.Printf("The multiplication of %d and %d is %dn", num1, num2, product)
}

Version 2

main.go

package main

import (
    "fmt"
    "github.com/yourname/calculatorv2/basic"
    "github.com/yourname/calculatorv2/advanced"
)

func main() {
    var num1 int = 1
    var num2 int = 2
    
    product := basic.Multiplication(num1, num2)
    square := advanced.Square(num2)

    fmt.Printf("The product of %d and %d is %dn", num1, num2, product)
    fmt.Printf("The square of %d is %dn", num2, square)
}

multiply.go

package basic

func Multiplication(x int, y int) int {
    return x * y
}

multiply_test.go

package basic

import "testing"

func TestMultiply(t *testing.T) {

    t.Run("multiplying two positive numbers", func(t *testing.T) {
        sum := Multiplication(2, 2)
        expected := 4
        
        if sum != expected {
            t.Errorf("Expected %d; but got %d", expected, sum)
        }
    })
    
    t.Run("multiplying two negative numbers", func(t *testing.T) {
        sum := Multiplication(-3, -4)
        expected := 12

        if sum != expected {
            t.Errorf("Expected %d; but got %d", expected, sum)
        }
    })

    t.Run("multiplying one positive and one negative integer", func(t *testing.T) {
        sum := Multiplication(1, -3)
        expected := -3

        if sum != expected {
            t.Errorf("Expected %d; but got %d", expected, sum)
        }
    })
    
}

square.go

package advanced

func Square(x int) int {
    return x * x
}

Version 3

main.go

package main

import (
    "fmt"
    "github.com/yourname/calculatorv3/basic"
    "github.com/yourname/calculatorv3/advanced"
    "github.com/yourname/calculatorv3/advanced/scientific"
)

func main() {
    var num1 int = 1
    var num2 int = 2
    var num3 float64 = 2
    
    product := basic.Multiplication(num1, num2)
    square := advanced.Square(num2)
    decimallog := scientific.DecimalLog(num3)

    fmt.Printf("The product of %d and %d is %dn", num1, num2, product)
    fmt.Printf("The square of %d is %dn", num2, square)
    fmt.Printf("The decimal log (base 10) of %f is %fn", num3, decimallog)
}

square.go

package advanced

func Square(x int) int {
    return x * x
}

declog.go

package scientific

import "math"

func DecimalLog(x float64) float64 {
    return math.Log10(x)
}

declog_test.go

package scientific

import "testing"

func TestDecimalLog(t *testing.T) {

    t.Run("adding two positive numbers", func(t *testing.T) {
        sum := DecimalLog(100)
        expected := 2.0
        
        if sum != expected {
            t.Errorf("Expected %f; but got %f", expected, sum)
        }
    })
    
    t.Run("adding two negative numbers", func(t *testing.T) {
        sum := DecimalLog(10)
        expected := 1.0

        if sum != expected {
            t.Errorf("Expected %f; but got %f", expected, sum)
        }
    })
}

Package is not in GOROOT is an error that occurs in a Go project when you have an error in your code or project configuration. If you want to know what caused this error and how to fix it, this article has it all.the package is not in goroot

We talked to our programming experts about this error, and they shared their experience with us. This means there is no compromise in what you’ll read and by the end of this article, you’ll have a solution.

Contents

  • Why a Package Is Not in Goroot? Detecting The Error
    • – Go111module Is Set to “On”
    • – Your Project Has Multiple go.mod Files
    • – You Are Using an Invalid Import Path
    • – You Are Using an Older Version of Go
  • How To Fix a Package That’s Not in Goroot
    • 1. Turn Off Go111module
    • 2. Remove Unnecessary go.mod Files
    • 3. Use the Right Import Path
    • 4. Update to the Latest Go Version
  • Conclusion

Why a Package Is Not in Goroot? Detecting The Error

A package is not in GOROOT because of the following:

  • GO111MODULE is set to “on”
  • Your project has multiple go.mod files
  • You are using an invalid import path to add the package
  • You are using an older version of Go

– Go111module Is Set to “On”

When you have GO111MODULE turned on in your environment variable, it can cause the “package is not in GOROOT” error. This happens because, before Go 1.11, you can only have your Go source code in the GOPATH.

Beginning in Go 1.11, hence GO111MODULE, Google introduced modules into Go programming. With this change, you can have your source code outside the GOPATH.

But it comes with a twist; your project must have a go.mod file. Consequently, if all the following are true, an error will occur when you try to build your project:

  • Your source code is not in the GOPATH
  • You don’t have the “go.mod” file
  • GO111MODULE is set to “on”

This happens because, with GO111MODULE turned on, Go will take your project as a module. As a result, it’ll be on the lookout for a go.mod file to manage other modules your project might depend on. Without it, you’ll get the error message “package XXX is not in GOROOT”. Where “XXX” is the name of your package.

– Your Project Has Multiple go.mod Files

Multiple go.mod files in a project lead to an error; this can happen if you do a “go mod init” in multiple folders in your project. Behind the scenes, every successful execution of this command leads to the creation of go.mod in a folder. You might know this until you try to build your project or run a command on the terminal.

That’s because Go will use one go.mod file to keep track of your project dependencies. In the case where you have more than one, our experience shows a conflict can occur. This leads to the “package is not in GOROOT” error when you run the build command in your terminal. With this information, you can inspect your project folder.

– You Are Using an Invalid Import Path

An invalid import path leads to the package ioutil is not in GOROOT error. If an invalid path exists in your code, Go can’t read the imported package, and it will show an error. It’s tricky to know if you have an invalid import path, so let’s see an example.Package Is Not in Goroot Causes

In our example, we have two Go source files; they are “multiarray.go” and “arrayapplication.go”.

The “multiarray.go” file is a package, so we place it in the “DesktopOurArrayApppkg” folder. Meanwhile, “arrayapplication.go” is the main source file, so we place it in the “DesktopOurArrayApp” folder.

Now, the following is the source code for “multiarray.go”:

package multiarray
var (
array_1 = []string{“p”, “u”, “t”}
array_2 = []string{“16”, “21”, “20”}
)

Now, the following is the source code for “arrayapplication.go”, but when you run the code using the “go” command on your command line. The cause of the error is an invalid path to “multiarray.go” in the “import” statement.

At this stage, if you run the code, you’ll see an error like “package is not in GOROOT (/usr/local/go/src/)” in your terminal.

package main
import (
“fmt”
variables “pkg/multiarray”
)
func main() {
w := variables.array_1
fmt.Println(w)
}

– You Are Using an Older Version of Go

An older version of Go SDK on your computer system can cause an error when you run your Go program. That’s because the team behind Go provides updates to include new features and bug fixes. Such an update can affect the code on your computer, which leads to an error.

For example, your Go code can contain new features added to the language. At the same time, if you have an older Go SDK on your computer, an error can occur if you run your code.

The cause of the error is compatibility issues between your code and the SDK installed on your computer.

You can fix a package that’s not in GOROOT using any of the following methods:

  • Turn off GO111MODULE
  • Remove unnecessary go.mod files from your code
  • Use the right import path to add the package
  • Update to the latest Go version

1. Turn Off Go111module

Turning off the GO111MODULE environment variable is a way to fix the package is not in GOROOT Windows error. By doing this, the GO runtime will use the legacy GOPATH mode. You can use the following steps to turn off GO111MODULE on your system:

  • Open your terminal.
  • Type the following: go env -w GO111MODULE=off
  • Hit enter on your keyboard.

At this point, the GO111MODULE environment variable is no longer active on your system. What’s more, if you download modules using the “go get” command, Go will use the legacy GOPATH mode.

Finally, turning off GO111MODULE will also fix the package is not in GOROOT VSCode error if you have a tool that does not support modules.

2. Remove Unnecessary go.mod Files

If your project has many go.mod files, you need to remove them except the one in the root folder. By doing this, the Go runtime can use that single go.mod file to manage the dependencies in the project.Package Is Not in Goroot Fixes

This will make your project clean, and you can prevent the “package is not in GOROOT” error. What’s more, if you choose to pass your project to another developer, let them know how everything works.

3. Use the Right Import Path

Using the right import is a fix for the Cobra package is not in GOROOT error message on your terminal. The same applies to our third example in this article; it had an invalid import path. As a result, Go will think that the imported package does not exist.

Again, we present the code for “multiarray.go” and “arrayapplication.go”; this time, we’ve corrected the error:

package multiarray
var (
array_1 = []string{“p”, “u”, “t”}
array_2 = []string{“16”, “21”, “20”}
)
package main
import (
“fmt”
variables “arrayapplication.go/pkg/multiarray” // The correction
)
func main() {
w := variables.array_1
fmt.Println(w)
}

The correction we made in the code above is the addition of “arrayapplication.go/”. This tells the Go runtime that “arrayapplication.go” is the entry point of the application. With this, when you run the code, you’ll not face any “package is not in GOROOT” errors.

What’s more, you can apply this method to solve Go 1.17 package is not in GOROOT errors. This type of error also occurs when you try to import a module from GitHub.

For example, the following code results in an error when you run the code:

import(
“fmt”
“unit”
)
baz := unit.FromFahrenheit(80)
fmt.Println(“The following is 80 Fahrenheit in Celsius = “, foo.Celsius())

The following is the updated code that includes the GitHub URL of the library. Also, if you are using Docker, having the correct path will prevent similar errors.

import(
“fmt”
“github.com/martinlindhe/unit” // By using the correct import path, the error is no more.
)
baz := unit.FromFahrenheit(80)
fmt.Println(“The following is 80 Fahrenheit in Celsius = “, foo.Celsius())

4. Update to the Latest Go Version

Software updates are very important for any system, and the Go SDK is no different. If you have an updated version of GOROOT on your system, you can write new code that will leverage new features. To update your Go SDK, do the following:

  • Open your web browser.
  • Navigate to the “Download and install” page on the Go documentation page.
  • Click on the “Download Go for X” button under number one (where X is your Operating System).
  • Scroll down to number two, and you’ll find three tabs.
  • Choose the tab for your Operating System and follow the installation instructions.

Conclusion

In this article, we analyzed the causes of a common Go error; “package is not in GOROOT.”. After that, we explained fixes that you could use, and the following is a summary of it all:

  • If you have GO111MODULE turned on, it can lead to the “package is not in GOROOT” error.
  • An invalid import path will lead to “package is not in GOROOT” when you run your code.
  • You can solve “package is not in GOROOT” by setting GO111MODULE to “off.”
  • If you import a Go library from GitHub, use the full URL to prevent a package error.
  • The fix to the package is not in GOROOT Docker error is to have a correct path in your configuration file.

The package is not in GOROOT is a common error that’s difficult to figure out. With everything that you’ve learned in this article, you can use Go packages without errors.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

What version of Go are you using (go version)?

$ go version
go version go1.14.2 linux/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output

$ go env

What did you do?

If a parent folder contained a go.mod this overrides the GOPATH setting and there is no clear indication this is happening.
lets say the following exists in the file system

and say you create a folder like

/work/projects/x/src/my/test2/main.go

and you export the GOPATH to point to your project

export GOPATH=/work/projects/x/

You will get an error like

can't load package: package my/test2 is not in GOROOT (/home/me/.gvm/gos/go1.14.2/src/my/test2)

And much time and head bashing will occur because you dont realize that go is using the /work/go.mod and overrides your GOPATH that you defined. This behavior is different then go 1.12 as well (it compiles without issue) so that adds to the confusion. (To be fair… I am totally guilty as sin for my own nasty creation, but there should be a better way of pointing out the root cause.)

What did you expect to see?

It would be great to see some reference to the go.mod file in the error message and not the GOROOT.

can't load package: package my/test2 is not in GOROOT (/home/me/.gvm/gos/go1.14.2/src/my/test2) with (/work/go.mod)

Or even more directly

can't load package: package my/test2 is not in go.mod (/work/my/test2)

I agree the former error is not wrong, but it is pointing in the wrong direction

What did you see instead?

can't load package: package my/test2 is not in GOROOT (/home/me/.gvm/gos/go1.14.2/src/my/test2)

Решил попробовать примеры с гитхаба.
Изначально библиотека импортировалась из гитхаба.
Типо так:

import (
	"context"
	"errors"
	"strconv"
	"strings"

	"github.com/adshao/go-binance"
)

Скачал этот архив . Переместил в папку. Переделал импорт.

import (
	"context"
	"errors"
	"strconv"
	"strings"

	"NeuroBot/binance/binance_2.2"
)

Jetbrains Go ошибок не выдавал.
Запускаю go build.
И получил ошибку:
binanceexchange.go:4:2: package NeuroBot/binance/binance_2.2 is not in GOROOT (C:UsersGroogogo1.16.3srcNeuroBotbinancebinance_2.2)

Подскажите пожалуйста)

The below error occurred when I had changed GOPATH, made two packages, and written some codes.

% package other/pkg1 is not in GOROOT (/usr/local/go/src/other/pkg1)

Enter fullscreen mode

Exit fullscreen mode

The cause is a package structure. Putting it together solves it.

Error

Below is the directory structure when the error occurred.

${GOPATH}/src
|-- other
|   |-- go.mod
|   `-- pkg1
|       `-- pkg1.go
`-- prj
    |-- go.mod
    `-- main.go

Enter fullscreen mode

Exit fullscreen mode

prj package is unable to refer to other/pkg1 although it is in GOPATH.

Codes are below.

prj/main.go

package main

import "other/pkg1"

func main()  {
    pkg1.Func()
}

Enter fullscreen mode

Exit fullscreen mode

other/pkg1/pkg1.go

package pkg1

import "fmt"

func Func() {
    fmt.Println("called func in pkg1")
}

Enter fullscreen mode

Exit fullscreen mode

Fix

To include other in prj solves the error.

${GOPATH}/src
`-- prj
    |-- go.mod
    |-- main.go
    `-- other
        `-- pkg1
            `-- pkg1.go

Enter fullscreen mode

Exit fullscreen mode

prj/main.go

package main

import "prj/other/pkg1"

func main()  {
    pkg1.Func()
}

Enter fullscreen mode

Exit fullscreen mode

Понравилась статья? Поделить с друзьями:
  • P5 код ошибки кондиционера что это
  • P420 ошибка форд фокус 2
  • P40914 oki ошибка датчика фотобарабана
  • P3513 ошибка камаз евро 5
  • P3513 ошибка can сообщения dm1dcu таймаут сообщения шины can