golang/go · error

invalid UTF-8 in %s=... value

Error message

invalid UTF-8 in %s=... value

What it means

Returned by checkEnvWrite as a final guard for any value written via `go env -w`: the value must be valid UTF-8. The go env config file is line-oriented text, so non-UTF-8 bytes would corrupt parsing on later reads.

Source

Thrown at src/cmd/go/internal/envcmd/env.go:694

		}
	case "CC", "CXX":
		if val == "" {
			break
		}
		args, err := quoted.Split(val)
		if err != nil {
			return fmt.Errorf("invalid %s: %v", key, err)
		}
		if len(args) == 0 {
			return fmt.Errorf("%s entry cannot contain only space", key)
		}
		if !filepath.IsAbs(args[0]) && args[0] != filepath.Base(args[0]) {
			return fmt.Errorf("%s entry is relative; must be absolute path: %q", key, args[0])
		}
	}

	if !utf8.ValidString(val) {
		return fmt.Errorf("invalid UTF-8 in %s=... value", key)
	}
	if strings.Contains(val, "\x00") {
		return fmt.Errorf("invalid NUL in %s=... value", key)
	}
	if strings.ContainsAny(val, "\v\r\n") {
		return fmt.Errorf("invalid newline in %s=... value", key)
	}
	return nil
}

func readEnvFileLines(mustExist bool) []string {
	file, _, err := cfg.EnvFile()
	if file == "" {
		if mustExist {
			base.Fatalf("go: cannot find go env config: %v", err)
		}
		return nil
	}

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Re-encode the value as UTF-8 before passing it to `go env -w`.
  2. Sanitize input via utf8.ValidString before invoking the command.
  3. Configure your terminal/editor/shell to use UTF-8.

Example fix

// before — value loaded from a latin-1 file
v := readLatin1(path) // contains 0xE9 etc.
goEnvW(key, v) // -> invalid UTF-8 in KEY=... value
// after — transcode to UTF-8 first
enc := charmap.ISO8859_1.NewDecoder()
v, _ = enc.String(v)
if !utf8.ValidString(v) { return fmt.Errorf("non-utf8") }
goEnvW(key, v)
Defensive patterns

Strategy: validation

Validate before calling

import "unicode/utf8"

if !utf8.ValidString(val) {
    return fmt.Errorf("value for %s is not valid UTF-8", key)
}

Prevention

When it happens

Trigger: Any `go env -w KEY=...` whose value byte sequence is not valid UTF-8 — e.g. raw latin-1/ISO-8859 bytes, binary garbage, or a value built from a non-UTF-8 source.

Common situations: Pasting paths from Windows terminals using legacy code pages; binary data accidentally fed via $env interpolation; reading values from files in non-UTF-8 encodings.

Understand the failure class

Related errors


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