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

Nicholas picture Nicholas · Jul 1, 2019 · Viewed 12.3k times · Source

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.

Answer

Itamar Lavender picture Itamar Lavender · Jul 18, 2019

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