cmd/go: mod init outside of GOPATH silently fails

Running `go mod init` outside of GOPATH with `GO111MODULE=off`
silently fails. This behavior was undocumented.

This CL makes go mod fail with the error:

   go: modules disabled by GO111MODULE=off; see 'go help modules'
Comparing with already erroring GO111MODULE=<value> conditions:

* With GO111MODULE=auto, inside GOPATH:
    go modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'
* With GO111MODULE=auto outside of GOPATH:
    go: cannot determine module path for source directory /path/to/dir (outside GOPATH, no import comments)

Fixes #31342

Change-Id: I749787d2a8640913c4ac263072d051314d76e778
GitHub-Last-Rev: b38447457d8cabed367ea4872cf7f238a49539c7
GitHub-Pull-Request: golang/go#31255
Reviewed-on: https://go-review.googlesource.com/c/go/+/170697
Reviewed-by: Bryan C. Mills <bcmills@google.com>
Run-TryBot: Bryan C. Mills <bcmills@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/src/cmd/go/internal/modcmd/init.go b/src/cmd/go/internal/modcmd/init.go
index 0f7421e..b94453b 100644
--- a/src/cmd/go/internal/modcmd/init.go
+++ b/src/cmd/go/internal/modcmd/init.go
@@ -35,6 +35,9 @@
 	if len(args) == 1 {
 		modload.CmdModModule = args[0]
 	}
+	if os.Getenv("GO111MODULE") == "off" {
+		base.Fatalf("go mod init: modules disabled by GO111MODULE=off; see 'go help modules'")
+	}
 	if _, err := os.Stat("go.mod"); err == nil {
 		base.Fatalf("go mod init: go.mod already exists")
 	}
diff --git a/src/cmd/go/testdata/script/mod_off_init.txt b/src/cmd/go/testdata/script/mod_off_init.txt
new file mode 100644
index 0000000..f9a4e10
--- /dev/null
+++ b/src/cmd/go/testdata/script/mod_off_init.txt
@@ -0,0 +1,7 @@
+env GO111MODULE=off
+
+# This script tests that running go mod init with
+# GO111MODULE=off when outside of GOPATH will fatal
+# with an error message.
+! go mod init
+stderr 'go mod init: modules disabled by GO111MODULE=off; see ''go help modules'''