github.com/zhongdalu/gf@v1.0.0/g/os/gfile/gfile_size.go (about)

     1  // Copyright 2017-2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gfile
     8  
     9  import (
    10  	"fmt"
    11  	"os"
    12  )
    13  
    14  // Size returns the size of file specified by <path> in byte.
    15  func Size(path string) int64 {
    16  	s, e := os.Stat(path)
    17  	if e != nil {
    18  		return 0
    19  	}
    20  	return s.Size()
    21  }
    22  
    23  // ReadableSize formats size of file given by <path>, for more human readable.
    24  func ReadableSize(path string) string {
    25  	return FormatSize(float64(Size(path)))
    26  }
    27  
    28  // FormatSize formats size <raw> for more human readable.
    29  func FormatSize(raw float64) string {
    30  	var t float64 = 1024
    31  	var d float64 = 1
    32  
    33  	if raw < t {
    34  		return fmt.Sprintf("%.2fB", raw/d)
    35  	}
    36  
    37  	d *= 1024
    38  	t *= 1024
    39  
    40  	if raw < t {
    41  		return fmt.Sprintf("%.2fK", raw/d)
    42  	}
    43  
    44  	d *= 1024
    45  	t *= 1024
    46  
    47  	if raw < t {
    48  		return fmt.Sprintf("%.2fM", raw/d)
    49  	}
    50  
    51  	d *= 1024
    52  	t *= 1024
    53  
    54  	if raw < t {
    55  		return fmt.Sprintf("%.2fG", raw/d)
    56  	}
    57  
    58  	d *= 1024
    59  	t *= 1024
    60  
    61  	if raw < t {
    62  		return fmt.Sprintf("%.2fT", raw/d)
    63  	}
    64  
    65  	d *= 1024
    66  	t *= 1024
    67  
    68  	if raw < t {
    69  		return fmt.Sprintf("%.2fP", raw/d)
    70  	}
    71  
    72  	return "TooLarge"
    73  }