github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/os/example_test.go (about)

     1  // Copyright 2016 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 os_test
     6  
     7  import (
     8  	"fmt"
     9  	"log"
    10  	"os"
    11  	"time"
    12  )
    13  
    14  func ExampleOpenFile() {
    15  	f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
    16  	if err != nil {
    17  		log.Fatal(err)
    18  	}
    19  	if err := f.Close(); err != nil {
    20  		log.Fatal(err)
    21  	}
    22  }
    23  
    24  func ExampleChmod() {
    25  	if err := os.Chmod("some-filename", 0644); err != nil {
    26  		log.Fatal(err)
    27  	}
    28  }
    29  
    30  func ExampleChtimes() {
    31  	mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC)
    32  	atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC)
    33  	if err := os.Chtimes("some-filename", atime, mtime); err != nil {
    34  		log.Fatal(err)
    35  	}
    36  }
    37  
    38  func ExampleFileMode() {
    39  	fi, err := os.Stat("some-filename")
    40  	if err != nil {
    41  		log.Fatal(err)
    42  	}
    43  
    44  	switch mode := fi.Mode(); {
    45  	case mode.IsRegular():
    46  		fmt.Println("regular file")
    47  	case mode.IsDir():
    48  		fmt.Println("directory")
    49  	case mode&os.ModeSymlink != 0:
    50  		fmt.Println("symbolic link")
    51  	case mode&os.ModeNamedPipe != 0:
    52  		fmt.Println("named pipe")
    53  	}
    54  }
    55  
    56  func ExampleIsNotExist() {
    57  	filename := "a-nonexistent-file"
    58  	if _, err := os.Stat(filename); os.IsNotExist(err) {
    59  		fmt.Printf("file does not exist")
    60  	}
    61  	// Output:
    62  	// file does not exist
    63  }
    64  
    65  func init() {
    66  	os.Setenv("USER", "gopher")
    67  	os.Setenv("HOME", "/usr/gopher")
    68  	os.Unsetenv("GOPATH")
    69  }
    70  
    71  func ExampleExpandEnv() {
    72  	fmt.Println(os.ExpandEnv("$USER lives in ${HOME}."))
    73  
    74  	// Output:
    75  	// gopher lives in /usr/gopher.
    76  }
    77  
    78  func ExampleLookupEnv() {
    79  	show := func(key string) {
    80  		val, ok := os.LookupEnv(key)
    81  		if !ok {
    82  			fmt.Printf("%s not set\n", key)
    83  		} else {
    84  			fmt.Printf("%s=%s\n", key, val)
    85  		}
    86  	}
    87  
    88  	show("USER")
    89  	show("GOPATH")
    90  
    91  	// Output:
    92  	// USER=gopher
    93  	// GOPATH not set
    94  }
    95  
    96  func ExampleGetenv() {
    97  	fmt.Printf("%s lives in %s.\n", os.Getenv("USER"), os.Getenv("HOME"))
    98  
    99  	// Output:
   100  	// gopher lives in /usr/gopher.
   101  }
   102  
   103  func ExampleUnsetenv() {
   104  	os.Setenv("TMPDIR", "/my/tmp")
   105  	defer os.Unsetenv("TMPDIR")
   106  }