完成基础脚手架

This commit is contained in:
LeeX
2022-05-09 09:00:14 +08:00
parent 632c76dfa6
commit 5fd8e0a694
37 changed files with 2867 additions and 0 deletions

63
utils/file.go Normal file
View File

@@ -0,0 +1,63 @@
package utils
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
"os"
)
type fileUtils struct{}
func FileUtils() *fileUtils {
return &fileUtils{}
}
func (f fileUtils) CheckIsExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// CheckAndCreate 判断文件名是否存在,不存在就创建
func (f fileUtils) CheckAndCreate(path string) error {
exists, err := f.CheckIsExists(path)
if err != nil {
return err
}
if !exists {
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
}
return nil
}
// DelPath 删除目录下的所有文件和目录本身
func (f fileUtils) DelPath(path string) error {
files, err := fileutil.ListFileNames(path)
if err != nil {
return err
}
for _, file := range files {
// 如果是目录,则递归删除
if fileutil.IsDir(file) {
err = f.DelPath(file)
if err != nil {
return err
}
} else {
err = fileutil.RemoveFile(fmt.Sprintf("%s/%s", path, file))
if err != nil {
return err
}
}
}
_ = fileutil.RemoveFile(path)
return nil
}

79
utils/http.go Normal file
View File

@@ -0,0 +1,79 @@
package utils
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
type httpUtil struct {
}
// Http 暴露接口
func Http() *httpUtil {
return &httpUtil{}
}
// NewProxy 重写创建代理函数,加入 Host 信息
func (hu httpUtil) NewProxy(target *url.URL) *httputil.ReverseProxy {
targetQuery := target.RawQuery
director := func(req *http.Request) {
req.Host = target.Host
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path, req.URL.RawPath = hu.joinURLPath(target, req.URL)
// 过滤掉参数
if uri, err := url.Parse(req.URL.Path); err == nil {
req.URL.Path = uri.Path
}
var rawQuery string
if targetQuery == "" || req.URL.RawQuery == "" {
rawQuery = targetQuery + req.URL.RawQuery
} else {
rawQuery = targetQuery + "&" + req.URL.RawQuery
}
req.URL.RawQuery = rawQuery
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
// 补充内部调用Header
req.Header.Set("X-Request-From", "internal")
}
return &httputil.ReverseProxy{Director: director}
}
func (hu httpUtil) joinURLPath(a, b *url.URL) (path, rawpath string) {
if a.RawPath == "" && b.RawPath == "" {
return hu.singleJoiningSlash(a.Path, b.Path), ""
}
// Same as singleJoiningSlash, but uses EscapedPath to determine
// whether a slash should be added
apath := a.EscapedPath()
bpath := b.EscapedPath()
aslash := strings.HasSuffix(apath, "/")
bslash := strings.HasPrefix(bpath, "/")
switch {
case aslash && bslash:
return a.Path + b.Path[1:], apath + bpath[1:]
case !aslash && !bslash:
return a.Path + "/" + b.Path, apath + "/" + bpath
}
return a.Path + b.Path, apath + bpath
}
func (hu httpUtil) singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}

24
utils/id.go Normal file
View File

@@ -0,0 +1,24 @@
package utils
import (
"fmt"
"math/rand"
"time"
)
type idUtil struct {
}
// Id 暴露接口
func Id() *idUtil {
return &idUtil{}
}
// GenOrderNo 生成订单Id
func (idUtil) GenOrderNo() string {
ss := time.Now().Format("20060102")
sss := time.Now().UnixNano() / 1e8
r := rand.Intn(1000)
n := fmt.Sprintf("%s%d%03d", ss, sss, r)
return n
}

31
utils/math.go Normal file
View File

@@ -0,0 +1,31 @@
package utils
import (
"fmt"
"gitee.ltd/lxh/logger"
"math"
"strconv"
)
type mathUtil struct{}
func MathUtil() *mathUtil {
return &mathUtil{}
}
func (m mathUtil) Sqrt(datas []float64, avg float64) float64 {
if len(datas) == 0 {
return 0
}
var aaa float64
for _, d := range datas {
co := d - avg
aaa += co * co
}
d, err := strconv.ParseFloat(fmt.Sprintf("%.2f", math.Sqrt(aaa/float64(len(datas)))), 64)
if err != nil {
logger.Say.Errorf("生成标准差失败:%v", err)
return 0
}
return d
}

14
utils/page.go Normal file
View File

@@ -0,0 +1,14 @@
package utils
// GenTotalPage 计算总页数
func GenTotalPage(count int64, size int) int {
totalPage := 0
if count > 0 {
upPage := 0
if int(count)%size > 0 {
upPage = 1
}
totalPage = (int(count) / size) + upPage
}
return totalPage
}

73
utils/random.go Normal file
View File

@@ -0,0 +1,73 @@
package utils
import (
"bytes"
"crypto/rand"
"fmt"
"math/big"
mr "math/rand"
"time"
)
type random struct{}
func Random() *random {
return &random{}
}
// GetRandomInt 获取指定长度的随机数字
func (r random) GetRandomInt(len int) string {
var numbers = []byte{0, 1, 2, 3, 4, 5, 7, 8, 9}
var container string
length := bytes.NewReader(numbers).Len()
for i := 1; i <= len; i++ {
rd, err := rand.Int(rand.Reader, big.NewInt(int64(length)))
if err != nil {
}
container += fmt.Sprintf("%d", numbers[rd.Int64()])
}
return container
}
// GetRandomNumber 获取指定范围内的一个随机数
func (r random) GetRandomNumber(min, max int) int {
mr.Seed(time.Now().UnixNano())
rn := mr.Intn(max-min) + min
return rn
}
// GetLiveHouseId 获取腾讯TRTC直播间Id
func (r random) GetLiveHouseId() string {
id := r.GetRandomNumber(1, 4294967295)
return fmt.Sprintf("%d", id)
}
// GetRandomString 生成随机字符串
func (r random) GetRandomString(len int) string {
var container string
var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
b := bytes.NewBufferString(str)
length := b.Len()
bigInt := big.NewInt(int64(length))
for i := 0; i < len; i++ {
randomInt, _ := rand.Int(rand.Reader, bigInt)
container += string(str[randomInt.Int64()])
}
return container
}
// GetRandomStringSafe 获取去掉了iI0O1的随机字符串
func (r random) GetRandomStringSafe(len int) string {
var container string
var str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789"
b := bytes.NewBufferString(str)
length := b.Len()
bigInt := big.NewInt(int64(length))
for i := 0; i < len; i++ {
randomInt, _ := rand.Int(rand.Reader, bigInt)
container += string(str[randomInt.Int64()])
}
return container
}

27
utils/time.go Normal file
View File

@@ -0,0 +1,27 @@
package utils
import (
"strings"
"time"
)
type timeUtils struct{}
func TimeUtils() *timeUtils {
return &timeUtils{}
}
// DurationString Duration转自定义String
func (tu timeUtils) DurationString(d time.Duration) string {
if d.Seconds() == 0 {
return "00:00:00"
}
s := d.String()
s = strings.ReplaceAll(s, "h", ":")
s = strings.ReplaceAll(s, "m", ":")
idx := strings.Index(s, ".")
if idx == -1 {
return s
}
return s[:idx]
}

20
utils/token.go Normal file
View File

@@ -0,0 +1,20 @@
package utils
import (
"golang.org/x/crypto/bcrypt"
)
// 生成Token的密钥写死防止乱改
//var jwtSecret = "qSxw4fCBBBecPsws"
// HashPassword 加密密码
func HashPassword(pass *string) {
bytePass := []byte(*pass)
hPass, _ := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost)
*pass = string(hPass)
}
// ComparePassword 校验密码
func ComparePassword(dbPass, pass string) bool {
return bcrypt.CompareHashAndPassword([]byte(dbPass), []byte(pass)) == nil
}