github.com/searKing/golang/go@v1.2.117/os/example_test.go (about)

     1  // Copyright 2022 The searKing Author. 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  	"strconv"
    11  	"strings"
    12  	"time"
    13  )
    14  import os_ "github.com/searKing/golang/go/os"
    15  
    16  func ExampleNewRotateFile() {
    17  	file := os_.NewRotateFile("log/test.2006-01-02-15-04-05.log")
    18  	defer file.Close()
    19  	file.MaxCount = 5
    20  	file.RotateInterval = 5 * time.Second
    21  	file.MaxAge = time.Hour
    22  	file.FileLinkPath = "log/s.log"
    23  	for i := 0; i < 10000; i++ {
    24  		time.Sleep(1 * time.Millisecond)
    25  		file.WriteString(time.Now().String())
    26  		if err := file.Rotate(false); err != nil {
    27  			fmt.Printf("%d, err: %v\n", i, err)
    28  		}
    29  	}
    30  }
    31  
    32  func ExampleNewRotateFileWithStrftime() {
    33  	file := os_.NewRotateFileWithStrftime("log/test.%Y-%m-%d-%H-%M-%S.log")
    34  	file.MaxCount = 5
    35  	file.RotateInterval = 5 * time.Second
    36  	file.MaxAge = time.Hour
    37  	file.FileLinkPath = "log/s.log"
    38  	for i := 0; i < 10000; i++ {
    39  		time.Sleep(1 * time.Millisecond)
    40  		file.WriteString(time.Now().String())
    41  		if err := file.Rotate(false); err != nil {
    42  			fmt.Printf("%d, err: %v\n", i, err)
    43  		}
    44  	}
    45  }
    46  
    47  func ExampleDiskUsage() {
    48  	total, free, avail, inodes, inodesFree, err := os_.DiskUsage("/tmp")
    49  	if err != nil {
    50  		return
    51  	}
    52  
    53  	fmt.Printf("total :%d B, free: %d B, avail: %d B, inodes: %d, inodesFree: %d", total, free, avail, inodes, inodesFree)
    54  	// total :499963174912 B, free: 57534603264 B, avail: 57534603264 B, inodes: 566386444, inodesFree: 561861360
    55  }
    56  
    57  func ExampleReadDirN() {
    58  	files, err := os_.ReadDirN(".", 1)
    59  	if err != nil {
    60  		log.Fatal(err)
    61  	}
    62  
    63  	for _, file := range files {
    64  		fmt.Println(file.Name())
    65  	}
    66  }
    67  
    68  func ExampleNewCacheFile() {
    69  	file := os_.NewCacheFile(os_.WithCacheFileBucketRootDir("log"),
    70  		os_.WithCacheFileCacheExpiredAfter(10*time.Millisecond),
    71  		os_.WithCacheFileBucketKeyFunc(func(url string) string {
    72  			return "always conflict key"
    73  		}))
    74  
    75  	for i := 0; i < 10000; i++ {
    76  		time.Sleep(1 * time.Millisecond)
    77  		_, _, err := file.Put(fmt.Sprintf("cache%d", i), strings.NewReader(strconv.Itoa(i)))
    78  		if err != nil {
    79  			fmt.Printf("%d, err: %v\n", i, err)
    80  		}
    81  	}
    82  }