github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/taste/walk.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"io/ioutil"
     8  	"path/filepath"
     9  	"runtime"
    10  	"strings"
    11  )
    12  
    13  func walk(dir string, f func(string) bool) bool {
    14  	fis, err := ioutil.ReadDir(dir)
    15  	if err != nil {
    16  		panic(err)
    17  	}
    18  	// parse all *.go files in directory;
    19  	// traverse subdirectories, but don't walk into testdata
    20  	for _, fi := range fis {
    21  		path := filepath.Join(dir, fi.Name())
    22  		if fi.IsDir() {
    23  			if fi.Name() != "testdata" {
    24  				if !walk(path, f) {
    25  					return false
    26  				}
    27  			}
    28  		} else if strings.HasSuffix(fi.Name(), ".go") && !strings.HasPrefix(fi.Name(), ".") {
    29  			if !f(path) {
    30  				return false
    31  			}
    32  		}
    33  	}
    34  	return true
    35  }
    36  
    37  func walkStdLib(f func(filename string) bool) {
    38  	walk(filepath.Join(runtime.GOROOT(), "src"), f)
    39  }
    40  
    41  func _() {
    42  	// example START OMIT
    43  	n := 0
    44  	println := func(s string) bool {
    45  		fmt.Println(n, s)
    46  		n++
    47  		return n < 10
    48  	}
    49  	walkStdLib(println)
    50  	// example END OMIT
    51  }
    52  
    53  func main() {
    54  	// main START OMIT
    55  	n := 0
    56  	walkStdLib(func(s string) bool {
    57  		fmt.Println(n, s)
    58  		n++
    59  		return n < 10
    60  	})
    61  	// main END OMIT
    62  }