Golang read-write filesystem interfaces
Wrapper around io.fs
interfaces to support read-write operations.
Its fully compatible with the fs
standard package to avoid duplicating
implementations.
Golang provides a read-only filesystem and numerous IO abstractions. That's
great to read files without mangling your code with OS details. For some reason
the designers decided to stop there, and provided no read-write interface. If
you need to write files, then you need to fallback and use concrete types such
as os.File
, which hardcodes the requirement to use a OS-level filesystem.
go-rwfs
provides:
- a
FS
interface based onfs.FS
with the extra methodOpenFile
- a
File
interface based onfs.File
with writer interfaces fromio
This means those interfaces are a drop-in replacement for any use-cases of the
fs
package where you now need write access as well.
Fetch the package:
go get github.com/wwmoraes/go-rwfs
Now you're good to Go 😉
Clone the repository then use make coverage
to run both unit and integration
tests.
The package comes with a concrete implementation for the OS filesystem, similar
to how the standard Golang distribution provides os.DirFS
:
package main
import "github.com/wwmoraes/go-rwfs"
// for brevity's sake there's no error checking, please forgive me ;)
func main() {
// create a sample folder and file with plain OS methods
os.Mkdir("foo", 0750)
osFile, _ := os.Create("foo/bar.txt")
osFile.Close()
// create a RWFS on the new folder
fsys := rwfs.OSDirFS("foo")
// read-only usage, same as with fs.FS
entries, _ := fs.ReadDir(fsys, "/")
for _, entry := range entries {
fmt.Println("file found:", entry.Name())
}
// read-write usage
fd, _ := fsys.OpenFile("bar.txt", os.O_WRONLY|os.O_TRUNC, 0640)
defer fd.Close()
fd.WriteString("hello from rwfs!")
}
- Golang - Base language
- @wwmoraes - Idea & Initial work