登录功能完成
This commit is contained in:
30
pkg/util/file.go
Normal file
30
pkg/util/file.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func Exists(name string) bool {
|
||||
if _, err := os.Stat(name); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func NotExists(name string) bool {
|
||||
return !Exists(name)
|
||||
}
|
||||
|
||||
func CreateNestedFile(path string) (*os.File, error) {
|
||||
basePath := filepath.Dir(path)
|
||||
if !Exists(basePath) {
|
||||
err := os.MkdirAll(basePath, 0700)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return os.Create(path)
|
||||
}
|
||||
36
pkg/util/rand.go
Normal file
36
pkg/util/rand.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
|
||||
|
||||
var src = rand.NewSource(time.Now().UnixNano())
|
||||
|
||||
const (
|
||||
// 6 bits to represent a letter index
|
||||
letterIdBits = 6
|
||||
// All 1-bits as many as letterIdBits
|
||||
letterIdMask = 1<<letterIdBits - 1
|
||||
letterIdMax = 63 / letterIdBits
|
||||
)
|
||||
|
||||
func RandStr(n int) string {
|
||||
b := make([]byte, n)
|
||||
// A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
|
||||
for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
|
||||
if remain == 0 {
|
||||
cache, remain = src.Int63(), letterIdMax
|
||||
}
|
||||
if idx := int(cache & letterIdMask); idx < len(letters) {
|
||||
b[i] = letters[idx]
|
||||
i--
|
||||
}
|
||||
cache >>= letterIdBits
|
||||
remain--
|
||||
}
|
||||
return *(*string)(unsafe.Pointer(&b))
|
||||
}
|
||||
21
pkg/util/slice.go
Normal file
21
pkg/util/slice.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package util
|
||||
|
||||
func InStringSlice(sl []string, ele string) bool {
|
||||
slMap := convertStrSlice2Map(sl)
|
||||
return inMap(slMap, ele)
|
||||
}
|
||||
|
||||
// ConvertStrSlice2Map 将字符串 slice 转为 map[string]struct{}。
|
||||
func convertStrSlice2Map(sl []string) map[string]struct{} {
|
||||
set := make(map[string]struct{}, len(sl))
|
||||
for _, v := range sl {
|
||||
set[v] = struct{}{}
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// InMap 判断字符串是否在 map 中。
|
||||
func inMap(m map[string]struct{}, s string) bool {
|
||||
_, ok := m[s]
|
||||
return ok
|
||||
}
|
||||
5
pkg/util/token.go
Normal file
5
pkg/util/token.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package util
|
||||
|
||||
func GenSessionID() string {
|
||||
return RandStr(32)
|
||||
}
|
||||
Reference in New Issue
Block a user