github.com/tada-team/tdproto@v1.51.57/utils.go (about)

     1  package tdproto
     2  
     3  import (
     4  	"crypto/rand"
     5  	"log"
     6  	"path/filepath"
     7  	"runtime"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/google/uuid"
    12  )
    13  
    14  func SourceDir() string {
    15  	_, filename, _, _ := runtime.Caller(0)
    16  	return filepath.Dir(filename)
    17  }
    18  
    19  func Gentime() int64 {
    20  	return time.Now().UnixNano()
    21  }
    22  
    23  func ValidUid(s string) bool {
    24  	if s == "" {
    25  		return false
    26  	}
    27  	_, err := uuid.Parse(s)
    28  	return err == nil
    29  }
    30  
    31  func IsoDatetime(dt time.Time) string {
    32  	s := dt.UTC().Format("2006-01-02T15:04:05.000000-0700")
    33  	return strings.Replace(s, "+0000", "Z", 1)
    34  }
    35  
    36  func ConfirmId() string {
    37  	return randomSymbols(12, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
    38  }
    39  
    40  func randomSymbols(n int, letters string) string {
    41  	bytes, err := randomBytes(n)
    42  	if err != nil {
    43  		log.Panicln("random bytes fail:", err)
    44  	}
    45  	for i, b := range bytes {
    46  		bytes[i] = letters[b%byte(len(letters))]
    47  	}
    48  	return string(bytes)
    49  }
    50  
    51  func randomBytes(n int) ([]byte, error) {
    52  	b := make([]byte, n)
    53  	if _, err := rand.Read(b); err != nil {
    54  		return nil, err
    55  	}
    56  	return b, nil
    57  }