golang/go · error

could not create module cache: %q is not a directory

Error message

could not create module cache: %q is not a directory

What it means

Thrown inside checkCacheDir when os.Stat succeeds (the path exists) but fi.IsDir() is false — the GOMODCACHE path resolves to a regular file, symlink-to-file, or device, not a directory. The module cache must be a directory.

Source

Thrown at src/cmd/go/internal/modfetch/cache.go:843

	}

	// os.Stat is slow on Windows, so we only call it once to prevent unnecessary
	// I/O every time this function is called.
	statCacheOnce.Do(func() {
		fi, err := os.Stat(cfg.GOMODCACHE)
		if err != nil {
			if !os.IsNotExist(err) {
				statCacheErr = fmt.Errorf("could not create module cache: %w", err)
				return
			}
			if err := os.MkdirAll(cfg.GOMODCACHE, 0o777); err != nil {
				statCacheErr = fmt.Errorf("could not create module cache: %w", err)
				return
			}
			return
		}
		if !fi.IsDir() {
			statCacheErr = fmt.Errorf("could not create module cache: %q is not a directory", cfg.GOMODCACHE)
			return
		}
	})
	return statCacheErr
}

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Identify what the path currently is: 'file $(go env GOMODCACHE)'.
  2. Remove or move the offending file: 'rm $(go env GOMODCACHE)'.
  3. Retry the go command — it will auto-create the directory.
  4. If the file was created by mistake, investigate which tool/script wrote it.

Example fix

# before: GOMODCACHE is a file
$ file $(go env GOMODCACHE)
/home/user/go/pkg/mod: ASCII text
# after
rm $(go env GOMODCACHE)
go build ./...
Defensive patterns

Strategy: validation

Validate before calling

func validateGOMODCACHEIsDir(gomodcache string) error {
    fi, err := os.Stat(gomodcache)
    if os.IsNotExist(err) {
        return nil // will be created
    }
    if err != nil {
        return err
    }
    if !fi.IsDir() {
        return fmt.Errorf("GOMODCACHE %q exists but is not a directory", gomodcache)
    }
    return nil
}

Type guard

null

Try / catch

null

Prevention

When it happens

Trigger: Running any module-aware go command when GOMODCACHE points at an existing file. Common after someone accidentally writes output to the cache path, or a misconfigured tool creates a file where a directory is expected.

Common situations: A stray 'go env -w GOMODCACHE=~/go' when ~/go was previously a file; a CI script that redirects output to the cache path; a symlink pointing at a file.

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/8424335022e14c4d. Report an issue: GitHub.