golangで一時ファイル作成ディレクトリを変更する

/tmpnoexec でマウントしているような環境だと go run hogehoge.go がこけたりする。

内部的に実行ファイルを /tmp に置いて実行しているのだろう。

実際、エラーメッセージは

1
2
$ go run hogehoge.go
fork/exec /tmp/go-build046683465/b001/exe/hogehoge: permission denied

となっている。

このような時は 環境変数 TMPDIR or GOTMPDIR を設定(上書き)してやれば良い。

1
2
$ env GOTMPDIR=$HOME/tmp go run hogehoge.go
Hoge Hoge

めでたしめでたし。

なお、 GOTMPDIRTMPDIR の違いについては version 1.10のchangelog に記載がある。

By default, the go tool creates its temporary files and directories in the system temporary directory (for example, $TMPDIR on Unix). If the new environment variable $GOTMPDIR is set, the go tool will creates its temporary files and directories in that directory instead.

特に指定しなければOSのテンポラリを使うが GOTMPDIR が指定されていればそちらを優先して使う、ということのようだ。