Skip to content

size

dstgo/size é uma biblioteca muito útil para conversão entre strings e tamanhos de arquivos

Endereço do repositório: dstgo/size: Fast conversion between file size and string (github.com)

Documentação: dstgo/size: Fast conversion between file size and string (github.com)

Instalação

$ go get https://github.com/dstgo/size

Uso

go
const (
  B  Size = 1
  KB      = B * 1024
  MB      = KB * 1024
  GB      = MB * 1024
  TB      = GB * 1024
  PB      = TB * 1024
)
go
type SizeMeta struct {
  Data float64
  Unit Size
}

Esta biblioteca é muito simples de usar, com apenas duas funções expostas:

go
func ParseSize(str string) SizeMeta

ParseSize converte uma string em uma estrutura SizeMeta, armazenando o tamanho dos dados e a unidade.

go
func ParseTargetSize(str string, size Size) SizeMeta

ParseTargetSize converte uma string em um SizeMeta de tamanho especificado.

Exemplo:

go
package main

import (
  "fmt"
  "github.com/dstgo/size"
)

func main() {
  parseSize := size.ParseSize("1.2MB")
  fmt.Printf("%+v\n", parseSize)
  fmt.Printf("%+v\n", parseSize.Round(1))

  parseSize1 := size.ParseSize("2.3-asdajl")
  fmt.Printf("%+v\n", parseSize1)

  targetSize := size.ParseTargetSize("2.65MB", size.KB)
  fmt.Printf("%+v", targetSize)
  fmt.Printf("%+v", targetSize.String())
}

Após a conversão, é possível usar o método Round para modificar quantas casas decimais manter, e também usar o método String para obter sua forma de string. Exemplo de saída:

1.20MB
1.2

2713.60KB

Golang por www.golangdev.cn edit