Меню

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

Для изучения 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 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,1591 gold badge4 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

3,7376 gold badges18 silver badges27 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

7703 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

1891 silver badge6 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

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

3293 silver badges4 bronze badges

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

1294 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,8232 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

3,9898 gold badges31 silver badges43 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

18.5k5 gold badges71 silver badges93 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

1671 silver badge9 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

3602 silver badges14 bronze badges

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 string to uint8 type casting [SOLVED]

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 WaitGroup Complete Tutorial [Beginners Guide]

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

# #go #go-modules #gopath

Вопрос:

Я установил Golang и столкнулся с go.mod file not found in current directory or any parent directory ошибкой в самый первый раз.

Но я работаю над <GOPATH>/src каталогом. Разве go.mod не требуется только в том случае, если текущий рабочий каталог находится вне GOPATH?

Вот подробная информация

Версия Go : go version go1.16.4 windows/amd64

Иди, завидуй :

 set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:Users<userName>AppDataLocalgo-build
set GOENV=C:Users<userName>AppDataRoaminggoenv
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:Users<userName>gopkgmod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:Users<userName>go
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.4
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:Users<userName>AppDataLocalTempgo-build4258913208=/tmp/go-build -gno-record-gcc-switches
 

Рабочий каталог: C:Users<userName>gosrcmain.go

Код :

 package main

import "fmt"

func main() {
    fmt.Println("HELLO")
}
 

И Ошибка:

 go: go.mod file not found in current directory or any parent directory; see 'go help modules'
Build process exiting with code: 1 signal: null
 

p.s. Я использую VS Code

Ответ №1:

«Команда go теперь по умолчанию создает пакеты в режиме с поддержкой модулей, даже если go.mod отсутствует».

«Вы можете установить для GO111MODULE значение auto, чтобы включить режим с поддержкой модулей, только если файл go.mod присутствует в текущем каталоге или в любом родительском каталоге».

В командной строке

 go env -w GO111MODULE=auto
 

Новые изменения в модуле Go 1.16

Ответ №2:

Начиная с версии 1.16, переменная GO111MODULE среды по умолчанию обрабатывается как «включено», что означает, что Go ожидает найти go.mod файл и больше не возвращается к GOPATH поведению до модуля.

Если вы хотите вернуться к поведению до 1.16, теперь вам нужно явно указать GO111MODULE=auto , но вам гораздо лучше создать go.mod файл.

Видеть https://golang.org/doc/go1.16#go-command и https://golang.org/ref/mod

Ответ №3:

Изучая также голанг, я также столкнулся с этой проблемой.

Это решило проблему для меня:

 go mod init
 

Это создаст базовый go.mod файл с информацией о модуле и версии для запуска go install при работе вне $GOPATH рабочей области. Я согласен с тем, чтобы узнать больше о системе модулей Go и не отключать env var, но встать и запустить это казалось прекрасным.

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

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.

1) Solution

Change this:

go env -w GO111MODULE=auto

to this:

go env -w GO111MODULE=off

2) Solution

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.

3) Solution

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!

4) Solution

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

5) Solution

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"]
6) Solution

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.

7) Solution

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.

8) Solution

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
9) Solution

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
10) Solution

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».

11) Solution
  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.

12) Solution

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

13) Solution

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}
$ go build ./project-one
$ go run ./project-one

Comments Section

Did you run go mod init as shown in How to Write Go Code, Getting Started, or Creating a Module?

Read and stick to golang.org/doc/#getting-started. You must use modules in Go 1.16.

Thank you! This works as building a docker image too — RUN go mod init in a Dockerfile 🙂

it worked man thanks but can you explain why it works ?

Thank you @Marcel for sharing this solution. I fixed my same error in this way.

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

this really works

Thanks, this was counterintuitive to me.

go mod init leads to go: cannot determine module path for source directory d:TMSU (outside GOPATH, module path must be specified).

Why does this work? What is it supposed to do? Are there some security implications of this change? What is the theory of operation?

In what context are GO111MODULE and GOPROXY set? Inside file go.mod? Or somewhere else?

Docker-related, presumably? How does that answer the question? What is «EXPOSE 6111» supposed to do? Why do GO111MODULE and GOPROXY not appear in this answer? What version of Docker and which host system (incl. version) was this tested on? Can you elaborate in your answer? (But without «Edit:», «Update:», or similar — the answer should appear as if it was written today.)

@pmor you need to specify the file path with the command , use go mod init ~/path_to_file.go

@PeterMortensen It should be set in your shell. It could be in a shells script too.

First make sure that your GO111MODULE value is set to «auto». You can check it from: bash go env if it is not set to «auto», run: bash go env -w GO111MODULE=auto go to your work directory in terminal and run: bash go mod init 'project_name' go mod tidy set to «off» again, or else your code won’t run, to do so, run: bash go env -w GO111MODULE=off You are good to Go!

Thanks, it was simple

Related Topics
linux
go

Mentions
Peter Mortensen
Lechat
Marcel
Farshad
Vlad Havriuk
Siwei
Spark Zeus
Dmotta
Erikric
Shwick
Chris Byron
Walexhino
Joseph Mulingwa Kithome
Vineesh P

References
66894200/error-message-go-go-mod-file-not-found-in-current-directory-or-any-parent-dire

0 / 0 / 0

Регистрация: 09.04.2021

Сообщений: 1

1

09.04.2021, 11:34. Показов 31346. Ответов 7


Здравствуйте, сегодня решил начать программировать на языке Go и у меня появился вопрос по поводу IDE. В интернете нашёл хорошую статью по настройке Visual Studio Code под язык Go. Всё установилось хорошо, но появилась проблема по настройке функции Debug. Когда нажимаю Run and Debug, выдаёт ошибку:
«go: go.mod file not found in current directory or any parent directory; see ‘go help modules’
exit status 1
Process exiting with code: 1″
Подскажите как пофиксить

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



3 / 3 / 0

Регистрация: 01.12.2017

Сообщений: 13

09.04.2021, 21:02

2

Версия Go 1.6?

Сначала (с этой версии так пошло) нужно дать команду в каталоге проекта: go mod init (если проект не планируется никуда выкладывать). Потом в получившийся файл модуля (go.mod) нужно прописать зависимости командой: go mod tidy.

И вот только потом собирать и/или отлаживать из IDE.

ЗЫЖ Мне лично такой процесс очень неудобен, но для кровавого энтерпрайза, говорят, очень надо 🙂



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

33803 / 18837 / 3972

Регистрация: 12.02.2012

Сообщений: 31,594

Записей в блоге: 12

10.04.2021, 11:53

3

Зачем сразу среду-то ставить, париться с настройками? Есть онлайн-компиляторы



0



0 / 0 / 0

Регистрация: 07.07.2019

Сообщений: 30

26.06.2021, 23:56

4

Столкнулся с таклой же проблемой. При запуске проекта получаю ошибку в консоли:
go: go.mod file not found in current directory or any parent directory; see ‘go help modules’
exit status 1
Process exiting with code: 1

Среда: Visual Studio Code

Выше советуют:

нужно дать команду в каталоге проекта: go mod init (если проект не планируется никуда выкладывать). Потом в получившийся файл модуля (go.mod) нужно прописать зависимости командой: go mod tidy.

Но не пойму где это делать.



0



Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.06.2021, 00:37

5

Цитата
Сообщение от mygedz
Посмотреть сообщение

Но не пойму где это делать.

Цитата
Сообщение от bope
Посмотреть сообщение

нужно дать команду в каталоге проекта

Еще раз?
То что каталог это папкаfolder это понятно? Папки создаются в проводнике.
Команды выполняются в консоли. Консоль это такое страшное черное окошко (в windows — это консоль интерпретатора cmd или powershell, в linux это консоль интерпретатора bash).
Курс по устройству ОС еще не проходил?

Добавлено через 5 минут

Цитата
Сообщение от bope
Посмотреть сообщение

Мне лично такой процесс очень неудобен

Для простых тестовых (не unit и т.д., а просто учебных) программ ничего этого делать не нужно. Никакого проекта — просто общая файлопомойка и команда go run файл для выполнения однофайловой программы. У меня работает. Только переменную среды GO111MODULE нужно выставить в auto.



0



0 / 0 / 0

Регистрация: 07.07.2019

Сообщений: 30

27.06.2021, 00:37

6

Цитата
Сообщение от Garry Galler
Посмотреть сообщение

Еще раз?
То что каталог это папкаfolder это понятно? Папки создаются в проводнике.
Команды выполняются в консоли. Консоль это такое страшное черное окошко (в windows — это консоль интерпретатора cmd или powershell, в linux это консоль интерпретатора bash).
Курс по устройству ОС еще не проходил?

Спасибо ха детальный ответ. Но к сожалению при запуске go mod init из папки проекта, я получаю:

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

Example usage:
‘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

Run ‘go help mod init’ for more information.



0



Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.06.2021, 00:48

7

Цитата
Сообщение от mygedz
Посмотреть сообщение

cannot determine module path

Цитата
Сообщение от Garry Galler
Посмотреть сообщение

Только переменную среды GO111MODULE нужно выставить в auto.

Как раз для случая outside GOPATH.

Добавлено через 8 минут
—————
А, я все понял. Ты же название проекта не указываешь: go mod init название_проекта

Добавлено через 1 минуту
Там же даже в ошибке написан пример: go mod init example.com/m



1



0 / 0 / 0

Регистрация: 07.07.2019

Сообщений: 30

27.06.2021, 01:03

8

Все теперь разобрался.

Но немного не понятно, почему это все автоматов при создании проекта не делается?



0



Hey I just updated to the new version of go go version go1.16.2 linux/amd64 and am getting an error when I build 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 then build again:

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

And same problem unfortunately.

12 Answers

Ahaha it worked! this is so awesome! 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 old version or everyone else just understood it properly I guess.

Change this:

go env -w GO111MODULE=auto

to this:

go env -w GO111MODULE=off

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 on your directory

go mod init

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"]

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 dir will become the root of the newly created module. See here to read about go modules.

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!

Try running 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

I had the same error when I build 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 been resolved adding in my Dockerfile the following lines, previously is required have Go project in modules, according the guide in previous posts :

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

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.

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/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».

  1. DO NOT install go in your home folder. e.g. ~/go, because this folder will be used by go in further third party libs’ 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. no need to go mod init

I have just started learning go.

And i have found this if you build your programme like below

go build «name of go app with path»

go build .Main.go

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Gms 50161 скания ошибка
  • Gms 50142 скания ошибка