123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- package utils
- import (
- "crypto/md5"
- "crypto/sha1"
- "database/sql"
- "encoding/hex"
- "fmt"
- "io"
- "mime/multipart"
- "os"
- "regexp"
- "time"
- )
- const (
- Person = iota + 1
- std
- ent
- cluster
- lite = 6
- )
- func SwitchLicenseType(license string) int {
- if regexp.MustCompile("(?i)标准").MatchString(license) {
- return std
- }
- if regexp.MustCompile("(?i)分布式").MatchString(license) {
- return cluster
- }
- if regexp.MustCompile("(?i)企业").MatchString(license) {
- return ent
- }
- if regexp.MustCompile("(?i)敏捷").MatchString(license) {
- return lite
- }
- if regexp.MustCompile("(?i)个人").MatchString(license) {
- return Person
- }
- return 0
- }
- const maxFileNameLength = 255
- func GenerateFileName(name, timestamp, ext string) string {
- newFileName := name + "_" + timestamp + ext
- if len(newFileName) > maxFileNameLength {
- trimLength := len(newFileName) - maxFileNameLength
- if len(name) > trimLength {
- name = name[:len(name)-trimLength]
- } else {
- name = ""
- }
- newFileName = name + "_" + timestamp + ext
- }
- return newFileName
- }
- func CalculateFileMd5(filePath string) (string, error) {
- file, err := os.Open(filePath)
- if err != nil {
- return "", err
- }
- defer file.Close()
- hash := md5.New()
- if _, err := io.Copy(hash, file); err != nil {
- return "", err
- }
- return hex.EncodeToString(hash.Sum(nil)), nil
- }
- func CalculateFileHeaderMd5(fileHeader *multipart.FileHeader) (string, error) {
- file, err := fileHeader.Open()
- if err != nil {
- return "", err
- }
- defer file.Close()
- hash := md5.New()
- if _, err := io.Copy(hash, file); err != nil {
- return "", err
- }
- return hex.EncodeToString(hash.Sum(nil)), nil
- }
- func GenerateShortIdentifier(username, email, telephone string) string {
-
- timestamp := time.Now().UnixNano()
-
- input := fmt.Sprintf("%s%s%s%d", timestamp, email, telephone, username)
-
- hasher := sha1.New()
- hasher.Write([]byte(input))
-
- return hex.EncodeToString(hasher.Sum(nil))[:12]
- }
- func ToString(ns sql.NullString) string {
- if ns.Valid {
- return ns.String
- }
- return ""
- }
- func ToInt64(ni sql.NullInt64) int64 {
- if ni.Valid {
- return ni.Int64
- }
- return 0
- }
- func ToTimeString(nt sql.NullTime) string {
- if nt.Valid {
- return nt.Time.Format(time.RFC3339)
- }
- return ""
- }
- func StringToNullString(s string) sql.NullString {
- if s == "" {
- return sql.NullString{
- String: "",
- Valid: false,
- }
- }
- return sql.NullString{
- String: s,
- Valid: true,
- }
- }
- func IntToNullInt64(i int64) sql.NullInt64 {
- return sql.NullInt64{
- Int64: i,
- Valid: true,
- }
- }
|