Source file src/io/fs/example_test.go

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fs_test
     6  
     7  import (
     8  	"fmt"
     9  	"io/fs"
    10  	"log"
    11  	"os"
    12  	"testing/fstest"
    13  )
    14  
    15  func ExampleGlob() {
    16  	fsys := fstest.MapFS{
    17  		"file.txt":        {},
    18  		"file.go":         {},
    19  		"dir/file.txt":    {},
    20  		"dir/file.go":     {},
    21  		"dir/subdir/x.go": {},
    22  	}
    23  
    24  	patterns := []string{
    25  		"*.txt",
    26  		"*.go",
    27  		"dir/*.go",
    28  		"dir/*/x.go",
    29  	}
    30  
    31  	for _, pattern := range patterns {
    32  		matches, err := fs.Glob(fsys, pattern)
    33  		if err != nil {
    34  			log.Fatal(err)
    35  		}
    36  		fmt.Printf("%q matches: %v\n", pattern, matches)
    37  	}
    38  
    39  	// Output:
    40  	// "*.txt" matches: [file.txt]
    41  	// "*.go" matches: [file.go]
    42  	// "dir/*.go" matches: [dir/file.go]
    43  	// "dir/*/x.go" matches: [dir/subdir/x.go]
    44  }
    45  
    46  func ExampleReadFile() {
    47  	fsys := fstest.MapFS{
    48  		"hello.txt": {
    49  			Data: []byte("Hello, World!\n"),
    50  		},
    51  	}
    52  
    53  	data, err := fs.ReadFile(fsys, "hello.txt")
    54  	if err != nil {
    55  		log.Fatal(err)
    56  	}
    57  
    58  	fmt.Print(string(data))
    59  
    60  	// Output:
    61  	// Hello, World!
    62  }
    63  
    64  func ExampleValidPath() {
    65  	paths := []string{
    66  		".",
    67  		"x",
    68  		"x/y/z",
    69  		"",
    70  		"..",
    71  		"/x",
    72  		"x/",
    73  		"x//y",
    74  		"x/./y",
    75  		"x/../y",
    76  	}
    77  
    78  	for _, path := range paths {
    79  		fmt.Printf("ValidPath(%q) = %t\n", path, fs.ValidPath(path))
    80  	}
    81  
    82  	// Output:
    83  	// ValidPath(".") = true
    84  	// ValidPath("x") = true
    85  	// ValidPath("x/y/z") = true
    86  	// ValidPath("") = false
    87  	// ValidPath("..") = false
    88  	// ValidPath("/x") = false
    89  	// ValidPath("x/") = false
    90  	// ValidPath("x//y") = false
    91  	// ValidPath("x/./y") = false
    92  	// ValidPath("x/../y") = false
    93  }
    94  
    95  func ExampleWalkDir() {
    96  	root := "/usr/local/go/bin"
    97  	fileSystem := os.DirFS(root)
    98  
    99  	fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
   100  		if err != nil {
   101  			log.Fatal(err)
   102  		}
   103  		fmt.Println(path)
   104  		return nil
   105  	})
   106  }
   107  

View as plain text