Every function in io/ioutil has been deprecated since Go 1.16. Nothing here is broken and old code still compiles, but new code should use the replacement named in each row.
Examples
Eight functions moved to two packages. The signatures are identical apart from ReadDir, so the change is a find and replace.
// Before After
ioutil.ReadFile(name) // os.ReadFile(name)
ioutil.WriteFile(...) // os.WriteFile(...)
ioutil.ReadAll(r) // io.ReadAll(r)
ioutil.ReadDir(dir) // os.ReadDir(dir) *different return
ioutil.TempFile(...) // os.CreateTemp(...)
ioutil.TempDir(...) // os.MkdirTemp(...)
ioutil.NopCloser(r) // io.NopCloser(r)
ioutil.Discard // io.Discard$ grep -rl ioutil . | xargs sed -i 's/ioutil\.ReadFile/os.ReadFile/g'
$ goimports -w .os.ReadFile and os.WriteFile are the same functions under a different name. The permission argument only applies when the file is created.
data, err := os.ReadFile("config.yaml")
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("out.txt", data, 0644)
if err != nil {
log.Fatal(err)
}os.ReadFile: writtenos.CreateTemp replaces ioutil.TempFile. In a test, t.TempDir is better than either: it makes a directory and removes it when the test ends.
f, err := os.CreateTemp("", "upload-*.json")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name())
defer f.Close()
// In a test, let the framework handle cleanup:
func TestThing(t *testing.T) {
dir := t.TempDir() // removed automatically
}/tmp/upload-2847193045.json| Function | Description |
|---|---|
ReadFile(filename string) ([]byte, error) os.ReadFile("config.yaml") | Deprecated since Go 1.16. Use os.ReadFile, which is the same function. |
WriteFile(filename string, data []byte, perm fs.FileMode) error os.WriteFile("out.txt", data, 0644) | Deprecated. Use os.WriteFile. |
ReadAll(r io.Reader) ([]byte, error) io.ReadAll(resp.Body) | Deprecated. Use io.ReadAll. |
ReadDir(dirname string) ([]fs.FileInfo, error) | Deprecated. Use os.ReadDir, which returns []fs.DirEntry instead and is cheaper. |
This is the only replacement that changes the return type, so it is the only one a find-and-replace will not fix. | |
TempFile(dir, pattern string) (*os.File, error) os.CreateTemp("", "upload-*.json") | Deprecated. Use os.CreateTemp. |
TempDir(dir, pattern string) (string, error) | Deprecated. Use os.MkdirTemp. In a test, prefer t.TempDir, which cleans up for you. |
NopCloser(r io.Reader) io.ReadCloser | Deprecated. Use io.NopCloser. |
Discard | Deprecated. Use io.Discard. |