github.com/grailbio/base@v0.0.11/file/example_localfile_test.go (about) 1 package file_test 2 3 import ( 4 "context" 5 "fmt" 6 "io/ioutil" 7 8 "github.com/grailbio/base/file" 9 ) 10 11 // Example_localfile is an example of basic read/write operations on the local 12 // file system. 13 func Example_localfile() { 14 doWrite := func(ctx context.Context, data []byte, path string) { 15 out, err := file.Create(ctx, path) 16 if err != nil { 17 panic(err) 18 } 19 if _, err = out.Writer(ctx).Write(data); err != nil { 20 panic(err) 21 } 22 if err := out.Close(ctx); err != nil { 23 panic(err) 24 } 25 } 26 27 doRead := func(ctx context.Context, path string) []byte { 28 in, err := file.Open(ctx, path) 29 if err != nil { 30 panic(err) 31 } 32 data, err := ioutil.ReadAll(in.Reader(ctx)) 33 if err != nil { 34 panic(err) 35 } 36 if err := in.Close(ctx); err != nil { 37 panic(err) 38 } 39 return data 40 } 41 42 ctx := context.Background() 43 doWrite(ctx, []byte("Blue box jumped over red bat"), "/tmp/foohah.txt") 44 fmt.Printf("Got: %s\n", string(doRead(ctx, "/tmp/foohah.txt"))) 45 // Output: 46 // Got: Blue box jumped over red bat 47 }