Created
January 29, 2021 16:11
-
-
Save bryanl/76e8cfebd4d81dc8a2b70ef06fed5254 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"github.com/davecgh/go-spew/spew" | |
) | |
func main() { | |
if err := run(); err != nil { | |
log.Printf("failed: %s", err) | |
os.Exit(1) | |
} | |
} | |
func run() error { | |
file := "/tmp/test.txt" | |
lines := []string{"one", "two", "three", "four"} | |
if err := File(file).Write().Lines(lines); err != nil { | |
return fmt.Errorf("write lines: %w", err) | |
} | |
got, err := File(file).Read().Lines() | |
if err != nil { | |
return fmt.Errorf("read lines: %w", err) | |
} | |
spew.Dump(got) | |
return nil | |
} | |
type Reader struct { | |
io.ReadCloser | |
err error | |
} | |
func (r *Reader) Lines() ([]string, error) { | |
if r.err != nil { | |
return nil, r.err | |
} | |
scanner := bufio.NewScanner(r.ReadCloser) | |
scanner.Split(bufio.ScanLines) | |
var out []string | |
for scanner.Scan() { | |
out = append(out, scanner.Text()) | |
} | |
if err := r.ReadCloser.Close(); err != nil { | |
return nil, err | |
} | |
return out, nil | |
} | |
type Writer struct { | |
io.WriteCloser | |
err error | |
} | |
func (w *Writer) Lines(in []string) error { | |
for i := range in { | |
if _, err := w.Write([]byte(in[i])); err != nil { | |
return err | |
} | |
if _, err := w.Write([]byte{'\n'}); err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
type FSAccessor struct { | |
path string | |
} | |
func (fa FSAccessor) Read() *Reader { | |
f, err := os.Open(fa.path) | |
return &Reader{ | |
ReadCloser: f, | |
err: err, | |
} | |
} | |
func (fa FSAccessor) Write() *Writer { | |
f, err := os.OpenFile(fa.path, os.O_WRONLY|os.O_CREATE, 0755) | |
return &Writer{ | |
WriteCloser: f, | |
err: err, | |
} | |
} | |
func File(p string) FSAccessor { | |
return FSAccessor{path: p} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment