Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Go build error "can't load package" with Go modules?

I'm setting up a new project using Go modules with this tutorial, and then trying to build it.

The module is located in a folder outside of the $GOPATH with the following structure:

example.com
├── my-project
├── ├── main
├── ├── ├── main.go
├── ├── go.mod

I've run go mod init example.com/my-project in directory example.com/my-project and created the go.mod file shown above.

main.go has basic contents:

package main

import (
"fmt"
)
func main(){
 fmt.Println("Hello, world!")
}

After attempting to run go build in directory example.com/my-project, I receive the following error message:

can't load package: package example.com/my-project: unknown import path "example.com/my-project": cannot find module providing package example.com/my-project.

I've also attempted to run go build in directory /, outside of example.com/my-project, and I get similar, failing results:

can't load package: package .: no Go files in ...

I'm probably getting some basic thing wrong, so thanks for your patience and any help you can give.

like image 635
Nicholas Avatar asked Jul 01 '19 16:07

Nicholas


People also ask

Where does go get install modules?

All downloaded modules are cached locally in your $GOPATH/pkg/mod directory by default. If you import a package to your project without downloading it first using go get , the latest tagged version of the module providing that package will be installed automatically and added to your go.

What is go build command?

The go build command compiles the packages named by the import paths, along with their dependencies into an executable. It it does not install the executable. This is the syntax of the command.

How do I install packages in go?

To install a package using go get follow the following steps: Step 1: Make sure to check whether the Golang is installed on your system by checking the version of Go. Step 2: Set the GOPATH by using the following command. Step 3: Now, set the PATH variable with the help of the following command.


1 Answers

no need for the directory main, just move your main.go and go.mod to example.com/my-project and it will work.

Project root should look like:

.
├── go.mod
└── main.go
like image 119
Itamar Lavender Avatar answered Oct 06 '22 02:10

Itamar Lavender