Golang afero: Difference between revisions

From wikinotes
No edit summary
Line 56: Line 56:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->
== Common Tasks ==
<blockquote>
<syntaxhighlight lang="go">
Fs := afero.NewOsFs()
Os := afero.Afero{Fs: Fs}
name, err := Os.TempDir(os.TempDir(), "my-prefix-")
exists, err := Os.Exists("/var/tmp/foo")
</syntaxhighlight>
</blockquote><!-- Common Tasks -->
</blockquote><!-- Usage -->
</blockquote><!-- Usage -->

Revision as of 19:42, 30 July 2022

Afero defines and implements an interface to access the filesystem.
You can then pass in an abstraction of real os calls, or a stub stub interface you can make assertions against.
It is maintained by the go developers.

Documentation

api docs https://pkg.go.dev/github.com/spf13/afero
github https://github.com/spf13/afero

Usage

Basics

// internal/fs/fs.go
import "github.com/spf13/afero"

Fs = Fs: afero.NewOsFs() // real 'os' calls
// foo.go
package foo
import (
    "example.com/x/mypkg/internal/fs"
    "github.com/spf13/afero"
)

func DoThing() {
    Os = afero.Afero{Fs: Fs}
    // os.* exposed on Fs
    Fs.Create("/var/tmp/foo.txt")

    // io, ioutil exposed in Afero{}
    Os.ReadFile("/var/tmp/foo.txt")
}
// foo_test.go
package foo

func TestDoThing(t *testing.T) {
    var fs.Fs = afero.NewMemMapFs()
    t.Run("Does Thing", func(t *testing.T) {
        err := foo.DoThing()
        assert.Nil(t, err)
    })
}

Common Tasks

Fs := afero.NewOsFs()
Os := afero.Afero{Fs: Fs}

name, err := Os.TempDir(os.TempDir(), "my-prefix-")
exists, err := Os.Exists("/var/tmp/foo")