github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/common/common.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package common 20 21 import ( 22 "crypto/md5" 23 crypto_rand "crypto/rand" 24 "encoding/hex" 25 "go/build" 26 "math/rand" 27 "os" 28 "path" 29 "strings" 30 "time" 31 ) 32 33 // DefaultPageSize ... 34 const DefaultPageSize int64 = 15 35 36 // create md5 string 37 func Strtomd5(s string) string { 38 h := md5.New() 39 h.Write([]byte(s)) 40 rs := hex.EncodeToString(h.Sum(nil)) 41 return rs 42 } 43 44 const ( 45 // Alphanum ... 46 Alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 47 // Alpha ... 48 Alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 49 // Number ... 50 Number = "0123456789" 51 ) 52 53 // RandStr ... 54 func RandStr(strSize int, dictionary string) string { 55 56 var bytes = make([]byte, strSize) 57 _, _ = crypto_rand.Read(bytes) 58 for k, v := range bytes { 59 bytes[k] = dictionary[v%byte(len(dictionary))] 60 } 61 return string(bytes) 62 } 63 64 // RandInt ... 65 func RandInt(min int, max int) int { 66 rand.Seed(time.Now().UnixNano()) 67 return min + rand.Intn(max-min) 68 } 69 70 // RandomString ... 71 func RandomString(l int) string { 72 bytes := make([]byte, l) 73 for i := 0; i < l; i++ { 74 bytes[i] = byte(RandInt(65, 129)) 75 } 76 return string(bytes) 77 } 78 79 // TestMode ... 80 func TestMode() bool { 81 return os.Getenv("TEST_MODE") == "true" 82 } 83 84 // Dir ... 85 func Dir() string { 86 dir, _ := os.Getwd() 87 gopath := os.Getenv("GOPATH") 88 if gopath == "" { 89 gopath = build.Default.GOPATH 90 } 91 project := path.Join(gopath, "src", "") 92 dir = strings.Replace(dir, project, "+", -1) 93 dir = strings.Replace(dir, "+/", "", -1) 94 return dir 95 } 96 97 func IsRunningInDockerContainer() bool { 98 // docker creates a .dockerenv file at the root 99 // of the directory tree inside the container. 100 // if this file exists then the viewer is running 101 // from inside a container so return true 102 103 if _, err := os.Stat("/.dockerenv"); err == nil { 104 return true 105 } 106 107 return false 108 }