Go mod file not found in current directory or any parent directory ошибка

I just updated to the new version of Go — Go version 1.16.2 Linux/amd64 and am getting an error when I build a Hello, World! example:

go: go.mod file not found in current directory or any parent directory; see ‘go help modules’

Even when I follow the fix from that post it isn’t working. I set these variables and then build again:

GO111MODULE=on
GOPROXY=https://proxy.golang.org,direct

And the same problem unfortunately.

Peter Mortensen's user avatar

asked Mar 31, 2021 at 19:33

shwick's user avatar

4

Change this:

go env -w GO111MODULE=auto

to this:

go env -w GO111MODULE=off

Vlad Havriuk's user avatar

answered May 19, 2021 at 6:44

Chris Byron's user avatar

Chris ByronChris Byron

2,4991 gold badge5 silver badges3 bronze badges

8

Yes, just follow the tutorial and for me that was doing go mod init test3 to create a module. No one else has been upgrading from the old version or everyone else just understood it properly I guess.

Peter Mortensen's user avatar

answered Apr 1, 2021 at 11:17

shwick's user avatar

shwickshwick

4,0776 gold badges21 silver badges28 bronze badges

2

First make sure that your GO111MODULE value is set to «auto».
You can check it from:

go env

If it is not set to «auto», then run:

go env -w GO111MODULE=auto

Go to your work directory in terminal and run:

go mod init
go mod tidy

You are good to go!

Peter Mortensen's user avatar

answered Aug 15, 2021 at 9:28

ch9xy's user avatar

ch9xych9xy

8704 silver badges6 bronze badges

3

From your project directory, add this line of code in your Dockerfile file if you are building a Docker image:

RUN go mod init

Or this in your directory:

go mod init

Peter Mortensen's user avatar

answered Jun 16, 2021 at 17:17

Walexhino's user avatar

WalexhinoWalexhino

1991 silver badge6 bronze badges

Go builds packages in module-aware mode by default starting from 1.16. See here.

Navigate to the folder containing the Go file and run:

go mod init <modulename>.

A go.mod file is created here and this directory will become the root of the newly created module. See here to read about Go modules.

Peter Mortensen's user avatar

answered Jun 16, 2021 at 5:31

SparkZeus's user avatar

SparkZeusSparkZeus

3383 silver badges5 bronze badges

This worked for me:

FROM golang:alpine

WORKDIR /go/src/app

ADD . .
RUN go mod init

RUN go build  -o /helloworld

EXPOSE 6111

CMD ["./helloworld"]

Peter Mortensen's user avatar

answered Jun 28, 2021 at 6:35

Joseph Mulingwa Kithome's user avatar

1

I was trying to run the go build command on my Windows local machine and I ran into the go: go.mod file not found in current directory or any parent directory; see 'go help modules' error.

This is how I went about solving it:

  • First I got the root directory of my application by running $ pwd and got a response like so /c/projects/go-projects/go-server
  • Then I ran $ go mod init c/projects/go-projects/go-server

This totally took away the error and I was able to run the server with the command $ ./go-web

PS: It is important to note that I was running Linux commands on my machine using the Git Bash Linux terminal for Windows, it comes by default in Windows with the installation of git for windows.

Peter Mortensen's user avatar

answered Jul 3, 2021 at 13:14

Marcel's user avatar

MarcelMarcel

1392 silver badges6 bronze badges

1

Try running the below commands

  • go mod init example.com/m‘ to initialize a v0 or v1 module
  • go mod init example.com/m/v2‘ to initialize a v2 module

Peter Mortensen's user avatar

answered Jul 7, 2021 at 13:35

Vineesh P's user avatar

I had the same error when I build a Docker image:

docker build . -t ms-c3alert:1.0.6

Error detail:

Step 11/21 : ENV GO111MODULE=on

 ---> Using cache
 ---> 1f1728be0f4a
Step 12/21 : RUN CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o c3alert .
 ---> Running in ee4b3d33d1d2
go: go.mod file not found in current directory or any parent directory; see 'go help modules'
The command '/bin/sh -c CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o c3alert .' returned a non-zero code: 1

I’ve resolved it by adding the following lines in my Dockerfile. Previously, it required to have a Go project in modules, according the guide in previous posts:

COPY go.mod .
COPY go.sum .
RUN go mod download

Peter Mortensen's user avatar

answered Jun 6, 2021 at 6:41

dmotta's user avatar

dmottadmotta

1,8332 gold badges21 silver badges32 bronze badges

I recently discovered that the «no required module» is the error message you get when trying to run/build a Go-file that doesn’t exist or has a typo.

My student had named his file ‘filename.Go’. The capital ‘G’ made it an invalid Go file, but Visual Studio Code still recognized it as a Go file, so it took a long time to discover it.

I spent a loooong time figuring this out, trying to understand modules and the relationship to folders, when the problem was a typo.

A confusing error message when it was actually the Go file, and not the .mod file that was «missing».

Peter Mortensen's user avatar

answered Aug 25, 2021 at 13:30

erikric's user avatar

erikricerikric

4,0398 gold badges32 silver badges44 bronze badges

  1. Do not install Go in your home folder. E.g. ~/go, because this folder will be used by To in further third party libraries’ installation

  2. download and unzip the Go install ZIP file to another place, e.g. /workspace/tools/go and set your PATH=/workspace/tools/go/bin

That’s it. There isn’t any need to do go mod init.

Peter Mortensen's user avatar

answered Sep 8, 2021 at 23:05

Siwei's user avatar

SiweiSiwei

19.5k6 gold badges74 silver badges94 bronze badges

just go to the parent directory and run go mod init "child/project root directory name"

answered Jul 1, 2022 at 12:04

Farshad's user avatar

FarshadFarshad

3372 silver badges9 bronze badges

I am using go v1.18. My problem was go work init.
See here for more detail:
VScode show me the error after I install the proxy in vscode

I had to do:

$ cd /my/parent/dir
$ go work init
$ go work use project-one
$ go work use project-two

Now I can do:

$ cd {root directory of the module where go.mod is}
$ cd ./project-one
$ go build .
$ go run .

answered Sep 4, 2022 at 15:29

lechat's user avatar

lechatlechat

3802 silver badges15 bronze badges

Для изучения Golang в качестве IDE взял VS Code.
Добавил плагин для Go. Указал $GOPATH$ (папка с проектами), в которой три папки {src, pkg, bin). Создал в папке src новый файл *.go с текстом программы «Hello world!».

текст программы

package main

import "fmt"

func main() {
	fmt.Println("hello world")
}

Запускается из командной строки без капризов, хоть через run, хоть через build. А вот Run без дебага (без дебага — чтоб не вылезли проблемы еще и Delve) из VS Code все время дает какие-то проблемы.
Одна из них —
всплывающее окно «Failed to continue: Check the debug console for details. [Open launch.json] [Cancel]«.
ХЗ что надо добавить/править в этом launch. json .
А в DEBUG CONSOLE «go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘.»
Но в программе нет никаких сторонних модулей. Только «import «fmt»» для PrintLn().
Нагуглил, что надо запустить «go mod init» — выполнил в консоли в папке проекта «go mod init test.go» — в папке проекта создался файл go.mod с содержимым
«module test
go 1.16 «

содержимое файла launch. json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch test function",
            "type": "go",
            "request": "launch",
            "mode": "test",
            "program": "${workspaceFolder}",
            "args": [
                "-test.run",
                "MyTestFunction"
            ]
        },
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}"
        },
        {
            "name": "Launch file",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "program": "${file}"
        }
    ]
}

Но при запуске Run без дебага все равно появляется сообщение про «go.mod not found».
Содержимое папки src:

  • go.mod (создан через go mod init test.go)
  • test.exe (создан через go build test.go)
  • test.go (текст программы Hello World)

В книгах про Go работа с кодом идет в командной строке и про подобное не упоминается, поскольку относиться к настройкам конкретной IDE.

Вопрос: какие настройки необходимо сделать с VS Code для «гладкой» работы с Golang и в частности избежать появления этого «проблема с go.mod«? Кто и почему не находит файл go.mod ?

I cannot build or use sys windows registry:

import (
	"golang.org/x/sys/windows/registry"
)
PS D:go_http_web_service> go build .http.go
http.go:24:2: no required module provides package golang.org/x/sys/windows/registry: go.mod file not found in current directory or any parent directory; see 'go help modules'

Version

go version go1.16.3 windows/amd64

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

go env Output

$ go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:UserschrisAppDataLocalgo-build
set GOENV=C:UserschrisAppDataRoaminggoenv
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:Userschrisgopkgmod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:Userschrisgo
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=C:Program FilesGo
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:Program FilesGopkgtoolwindows_amd64
set GOVCS=
set GOVERSION=go1.16.3
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=NUL
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:UserschrisAppDataLocalTempgo-build3911830538=/tmp/go-build -gno-record-gcc-switches

To fix the go: go.mod file not found in current directory or any parent directory error in Golang, you can create a go.mod file using the go mod init <module_name> command or use this command: go env -w GO111MODULE=off.

The “go: go.mod file not found in current directory or any parent directory” error occurs when you try to use Go modules, but there isn’t a go.mod file in the current directory or any parent directory.

Let’s initialize a go module using the below command in your project’s root directory:

go mod init <module_name>

Replace <module_name> with a name for your module. Typically, the module name is the repository URL where your code will be hosted. For example:

go mod init github.com/yourusername/yourproject

This command will create a go.mod file in the current directory with the provided module name. The go.mod file manages your project’s dependencies and other module-related settings.

After initializing your project as a Go module, you can use Go commands like go build, go test, and go run without encountering the go.mod file not found error.

That’s it.

Krunal Lathiya Author

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.

In this blog, I will try to cover the fundamentals of the go module, go.mod file, and how to solve go.mod file not found.

Overview on go.mod file in golang

A module is a collection of one or more related packages that provide a discrete and useful set of functions. For example, you could create a module with packages that contain functions for performing financial analysis so that others who are developing financial applications can use your work. See the Developing and publishing modules for more information.

Go code is divided into packages, and packages are further divided into modules. Your module specifies the dependencies required to run your code, such as the Go version and a set of other modules.

To start your module, use the go mod init command:

go mod init [module-path]: The go mod init command initializes and writes a new go.mod file in the current directory, in effect creating a new module rooted at the current directory. The go.mod file must not already exist. init accepts one optional argument, the module path for the new module. See Module paths for instructions on choosing a module path. If the module path argument is omitted, init will attempt to infer the module path using import comments in .go files, vendoring tool configuration files, and the current directory (if in GOPATH).

$ go mod init example.com/golinuxcloud
go: creating new go.mod: module example.com/golinuxcloud

If you are not in GOPATH directory, make sure to enter the path or this error will appear:

go: cannot determine module path for source directory C:UsersadminDesktopgolanggolang3greetings (outside GOPATH, module path must be specified)

The go mod init command creates a go.mod file to track your code’s dependencies. At first, the file includes only the name of your module and the Go version your code supports. But as you add dependencies, the go.mod file will list the versions your code depends on. This keeps builds reproducible and gives you direct control over which module versions to use.

ALSO READ: Golang Compare String PROPERLY [3 Methods]

And now you can install any libraries or packages using go get command:

PS C:UsersadminDesktopgolanggolang3greetings> go get github.com/spf13/viper
go: added github.com/fsnotify/fsnotify v1.5.4
go: added github.com/hashicorp/hcl v1.0.0
go: added github.com/magiconair/properties v1.8.6
go: added github.com/mitchellh/mapstructure v1.5.0
go: added github.com/pelletier/go-toml v1.9.5
go: added github.com/pelletier/go-toml/v2 v2.0.5
go: added github.com/spf13/afero v1.8.2
go: added github.com/spf13/cast v1.5.0
go: added github.com/spf13/jwalterweatherman v1.1.0
go: added github.com/spf13/pflag v1.0.5
go: added github.com/spf13/viper v1.13.0
go: added github.com/subosito/gotenv v1.4.1
go: added golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a
go: added golang.org/x/text v0.3.7
go: added gopkg.in/ini.v1 v1.67.0
go: added gopkg.in/yaml.v2 v2.4.0
go: added gopkg.in/yaml.v3 v3.0.1

And the go.mod file:

module greeting

go 1.19

require (
	github.com/fsnotify/fsnotify v1.5.4 // indirect
	github.com/hashicorp/hcl v1.0.0 // indirect
	github.com/magiconair/properties v1.8.6 // indirect
	github.com/mitchellh/mapstructure v1.5.0 // indirect
	github.com/pelletier/go-toml v1.9.5 // indirect
	github.com/pelletier/go-toml/v2 v2.0.5 // indirect
	github.com/spf13/afero v1.8.2 // indirect
	github.com/spf13/cast v1.5.0 // indirect
	github.com/spf13/jwalterweatherman v1.1.0 // indirect
	github.com/spf13/pflag v1.0.5 // indirect
	github.com/spf13/viper v1.13.0 // indirect
	github.com/subosito/gotenv v1.4.1 // indirect
	golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
	golang.org/x/text v0.3.7 // indirect
	gopkg.in/ini.v1 v1.67.0 // indirect
	gopkg.in/yaml.v2 v2.4.0 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)

How to solve “go.mod file not found” error?

We have to work with GO111MODULE environment. The go command now builds packages in module-aware mode by default, even when no go.mod is present. This is a big step toward using modules in all projects. It’s still possible to build packages in GOPATH mode by setting the GO111MODULE environment variable to off. You can also set GO111MODULE to auto to enable module-aware mode only when a go.mod file is present in the current directory or any parent directory. This was previously the default.

ALSO READ: Golang Mutex Tutorial [Lock() & Unlock() Examples]

Solution-1: Create go.mod file using “go mod init”

Make sure that your GO111MODULE value is set to «auto». You can check it by the command:

$ go env GO111MODULE

If it is not set to «auto», then run:

$ go env -w GO111MODULE=auto

Go to your working directory then then try to create go.mod file:

$ go mod init [your-working-folder]

For example if your working directory is /opt/goexamples/helloworld then

$ cd /opt/goexamples/helloworld
$ go mod init helloworld

This will create a go.mod file for helloworld package.

Solution-2: Update the GO111MODULE environment

This was previously the default. Now you have to set GO111MODULE permanently with go env -w:

$ go env -w GO111MODULE=off

GO111MODULE=off forces Go to behave the GOPATH way, even outside of GOPATH

Summary

In this article, I showed you how to use go.mod file as well as how to fix go.mod file not found error. Hopefully through the article, you have a better understanding of how to organize code and modules in golang.

References:

https://go.dev/blog/go116-module-changes
https://go.dev/ref/mod#go-mod-init
https://go.dev/doc/tutorial/create-module

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

Возможно, вам также будет интересно:

  • Gms 50161 скания ошибка
  • Gms 50142 скания ошибка
  • Gmaptool ошибка при создании выходного файла
  • Gmail произошла ошибка повторите попытку позже
  • Gmail подтверждение не отправлено произошла ошибка повторите попытку

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии