feat: add Go backend

This commit is contained in:
richjohnrambo
2026-10-10 20:56:17 +08:00
parent 50fcfd2d3d
commit f6024f0964
1040 changed files with 107169 additions and 0 deletions
View File
+74
View File
@@ -0,0 +1,74 @@
// Package charset
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package charset
import (
"bytes"
"crypto/rand"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gutil"
r "math/rand"
"strings"
"time"
)
// RandomCreateBytes 生成随机字串符
func RandomCreateBytes(n int, alphabets ...byte) []byte {
if len(alphabets) == 0 {
alphabets = []byte(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`)
}
var bytes = make([]byte, n)
var randBy bool
if num, err := rand.Read(bytes); num != n || err != nil {
randBy = true
}
for i, b := range bytes {
if randBy {
bytes[i] = alphabets[r.New(r.NewSource(time.Now().UnixNano())).Intn(len(alphabets))]
} else {
bytes[i] = alphabets[b%byte(len(alphabets))]
}
}
return bytes
}
// ParseErrStack 解析错误的堆栈信息
func ParseErrStack(err error) []string {
return ParseStack(gerror.Stack(err))
}
// ParseStack 解析堆栈信息
func ParseStack(st string) []string {
stack := gstr.Split(st, "\n")
for i := 0; i < len(stack); i++ {
stack[i] = gstr.Replace(stack[i], "\t", "--> ")
}
return stack
}
// SerializeStack 解析错误并序列化堆栈信息
func SerializeStack(err error) string {
buffer := bytes.NewBuffer(nil)
gutil.DumpTo(buffer, ParseErrStack(err), gutil.DumpOption{
WithType: false,
ExportedOnly: false,
})
return buffer.String()
}
// SubstrAfter 截取指定字符后的内容
func SubstrAfter(str string, symbol string) string {
comma := strings.Index(str, symbol)
if comma < 0 { // -1 不存在
return ""
}
pos := strings.Index(str[comma:], symbol)
if comma+pos+1 > len(str) {
return ""
}
return str[comma+pos+1:]
}
+166
View File
@@ -0,0 +1,166 @@
// Package convert
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package convert
import (
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/utility/validate"
"reflect"
"unicode"
"unsafe"
)
var (
descTags = []string{"description", "dc", "json"} // 实体描述标签
fieldTags = []string{"json"} // 实体字段名称映射
)
// GetModelTable 获取模型中的表定义
func GetModelTable(m *gdb.Model) (tablesInit, tables string) {
if m == nil {
return "", ""
}
v := reflect.ValueOf(m).Elem()
t := reflect.TypeOf(m).Elem()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
val := v.Field(i)
if field.Name == "tablesInit" {
tablesInit = reflect.NewAt(val.Type(), unsafe.Pointer(val.UnsafeAddr())).Elem().String()
tablesInit = gstr.Replace(tablesInit, "`", "")
continue
}
if field.Name == "tables" {
tables = reflect.NewAt(val.Type(), unsafe.Pointer(val.UnsafeAddr())).Elem().String()
continue
}
}
return
}
// EscapeFieldsToSlice 将转义过的字段转换为字段集切片
func EscapeFieldsToSlice(s string) []string {
return gstr.Explode(",", gstr.Replace(gstr.Replace(s, "`,`", ","), "`", ""))
}
// GetMapKeys 获取map的所有key
func GetMapKeys[K comparable](m map[K]any) []K {
j := 0
keys := make([]K, len(m))
for k := range m {
keys[j] = k
j++
}
return keys
}
// CamelCaseToUnderline 驼峰单词转下划线单词
func CamelCaseToUnderline(s string) string {
var output []rune
for i, r := range s {
if i == 0 {
output = append(output, unicode.ToLower(r))
} else {
if unicode.IsUpper(r) {
output = append(output, '_')
}
output = append(output, unicode.ToLower(r))
}
}
return string(output)
}
// GetEntityFieldTags 获取实体中的字段名称
func GetEntityFieldTags(entity interface{}) (tags []string, err error) {
var formRef = reflect.TypeOf(entity)
for i := 0; i < formRef.NumField(); i++ {
field := formRef.Field(i)
if field.Type.Kind() == reflect.Struct {
addTags, err := reflectTag(field.Type, fieldTags, []string{})
if err != nil {
return nil, err
}
tags = append(tags, addTags...)
continue
}
tags = append(tags, reflectTagName(field, fieldTags, true))
}
return
}
// GetEntityDescTags 获取实体中的描述标签
func GetEntityDescTags(entity interface{}) (tags []string, err error) {
var formRef = reflect.TypeOf(entity)
for i := 0; i < formRef.NumField(); i++ {
field := formRef.Field(i)
if field.Type.Kind() == reflect.Struct {
addTags, err := reflectTag(field.Type, descTags, []string{})
if err != nil {
return nil, err
}
tags = append(tags, addTags...)
continue
}
tags = append(tags, reflectTagName(field, descTags, true))
}
return
}
// reflectTag 层级递增解析tag
func reflectTag(reflectType reflect.Type, filterTags []string, tags []string) ([]string, error) {
if reflectType.Kind() == reflect.Ptr {
return nil, gerror.Newf("reflect type do not support reflect.Ptr yet, reflectType:%+v", reflectType)
}
if reflectType.Kind() != reflect.Struct {
return nil, nil
}
for i := 0; i < reflectType.NumField(); i++ {
tag := reflectTagName(reflectType.Field(i), filterTags, false)
if tag == "" {
addTags, err := reflectTag(reflectType.Field(i).Type, filterTags, tags)
if err != nil {
return nil, err
}
tags = append(tags, addTags...)
continue
}
tags = append(tags, tag)
}
return tags, nil
}
// reflectTagName 解析实体中的描述标签,优先级:description > dc > json > Name
func reflectTagName(field reflect.StructField, filterTags []string, isDef bool) string {
if validate.InSlice(filterTags, "description") {
if description, ok := field.Tag.Lookup("description"); ok && description != "" {
return description
}
}
if validate.InSlice(filterTags, "dc") {
if dc, ok := field.Tag.Lookup("dc"); ok && dc != "" {
return dc
}
}
if validate.InSlice(filterTags, "json") {
if jsonName, ok := field.Tag.Lookup("json"); ok && jsonName != "" {
return jsonName
}
}
if !isDef {
return ""
}
return field.Name
}
+115
View File
@@ -0,0 +1,115 @@
// Package convert
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package convert
import (
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/utility/validate"
)
// IpFilterStrategy ip过滤策略
func IpFilterStrategy(originIp string) (list map[string]struct{}) {
list = make(map[string]struct{})
// 所有IP
if originIp == "*" {
list["*"] = struct{}{}
return
}
// 多个IP
if gstr.Contains(originIp, ",") {
ips := gstr.Explode(",", originIp)
if len(ips) > 0 {
for _, ip := range ips {
if !validate.IsIp(ip) {
continue
}
list[ip] = struct{}{}
}
}
return
}
// IP段
if gstr.Contains(originIp, "/24") {
segment := gstr.Replace(originIp, "/24", "")
if !validate.IsIp(segment) {
return
}
var (
start = gstr.Explode(".", segment)
prefix = gstr.Implode(".", start[:len(start)-1]) + "."
index = gconv.Int(start[len(start)-1])
)
if index < 1 {
index = 1
}
for i := index; i <= 254; i++ {
list[prefix+gconv.String(i)] = struct{}{}
}
return
}
// IP范围
if gstr.Contains(originIp, "-") {
originIps := gstr.Explode("-", originIp)
if len(originIps) != 2 {
return
}
if !validate.IsIp(originIps[0]) || !validate.IsIp(originIps[1]) {
return
}
var (
start = gstr.Explode(".", originIps[0])
prefix = gstr.Implode(".", start[:len(start)-1]) + "."
startIndex = gconv.Int(gstr.SubStrFromREx(originIps[0], "."))
endIndex = gconv.Int(gstr.SubStrFromREx(originIps[1], "."))
)
if startIndex >= endIndex {
list[originIps[0]] = struct{}{}
return
}
if startIndex < 1 {
startIndex = 1
}
if endIndex > 254 {
endIndex = 254
}
for i := startIndex; i <= endIndex; i++ {
list[prefix+gconv.String(i)] = struct{}{}
}
return
}
// 指定IP
if validate.IsIp(originIp) {
list[originIp] = struct{}{}
return
}
return list
}
// MatchIpStrategy 匹配IP策略,输入ip如果在策略当中返回true
func MatchIpStrategy(rules, ip string) bool {
allowedIps := IpFilterStrategy(rules)
if _, ok := allowedIps["*"]; ok {
return true
}
_, ok := allowedIps[ip]
return ok
}
+59
View File
@@ -0,0 +1,59 @@
// Package convert
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package convert
// UniqueSlice 切片去重
func UniqueSlice[K comparable](languages []K) []K {
result := make([]K, 0, len(languages))
temp := map[K]struct{}{}
for _, item := range languages {
if _, ok := temp[item]; !ok {
temp[item] = struct{}{}
result = append(result, item)
}
}
return result
}
func Remove(sl []interface{}, f func(v1 interface{}) bool) []interface{} {
for k, v := range sl {
if f(v) {
sl[k] = sl[len(sl)-1]
sl = sl[:len(sl)-1]
return sl
}
}
return sl
}
func RemoveSlice[K comparable](src []K, sub K) []K {
for k, v := range src {
if v == sub {
copy(src[k:], src[k+1:])
return src[:len(src)-1]
}
}
return src
}
// DifferenceSlice 比较两个切片,返回他们的差集
// slice1 := []int{1, 2, 3, 4, 5}
// slice2 := []int{4, 5, 6, 7, 8}
// fmt.Println(Difference(slice1, slice2)) // Output: [1 2 3]
func DifferenceSlice[T comparable](s1, s2 []T) []T {
m := make(map[T]bool)
for _, item := range s1 {
m[item] = true
}
var diff []T
for _, item := range s2 {
if _, ok := m[item]; !ok {
diff = append(diff, item)
}
}
return diff
}
+11
View File
@@ -0,0 +1,11 @@
# 数据库补丁支持
> 将用于抹平不同数据库的差异性,以支撑基于数据库的部分特性。
## 特性
- 增加对数据库表字段注释的支持,特别是 sqlite 的注释支持。
- 增加对数据库表名注释的支持,特别是 sqlite 的注释支持。
> 注意以上支持中,由于 sqlite 的特殊性,对 sqlite 表创建的 sql 语句有所要求,具体示例请参考 [sqlite_example.sql](./sqlite_example.sql)
+54
View File
@@ -0,0 +1,54 @@
package db
import (
"context"
"fmt"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// 获取数据库表字段及注释
// usage:
//
// fields, err := db.GetFieldsWithComment(ctx, in.Table, in.Name)
// if err != nil {
// return
// }
// for _, v := range fields {}
func GetFieldsWithComment(ctx context.Context, tableName, dbTag string) (fields map[string]*gdb.TableField, err error) {
db := g.DB(dbTag)
fields, err = db.TableFields(ctx, tableName) // 使用 goframe 框架本身已完美支持 mysql 获取表字段及注释
dbConf := db.GetConfig()
switch dbConf.Type {
case "sqlite":
fields, err = fixSqliteFieldsComment(ctx, tableName, db, fields)
}
return
}
type TableComment struct {
Name string `json:"name"`
Comment string `json:"comment"`
}
// 获取数据库表字段及注释
func GetTablesWithComment(ctx context.Context, dbTag string) (tables []*TableComment, err error) {
db := g.DB(dbTag)
dbConf := db.GetConfig()
switch dbConf.Type {
case "mysql":
sql := "SELECT TABLE_NAME as name, TABLE_COMMENT as comment FROM information_schema.`TABLES` WHERE TABLE_SCHEMA = '%s'"
if err = db.Ctx(ctx).Raw(fmt.Sprintf(sql, dbConf.Name)).Scan(&tables); err != nil {
return
}
case "sqlite":
var tableNames []string
tableNames, err = db.Tables(ctx)
if err != nil {
return
}
tables, err = transSqliteTablesComment(ctx, tableNames, db)
}
return
}
+45
View File
@@ -0,0 +1,45 @@
CREATE TABLE IF NOT EXISTS `user1` ( -- 用户管理
`id` INTEGER, -- 编号
`name` VARCHAR(50), -- 名称
`email` VARCHAR(255), -- 邮箱
`address` TEXT, -- 地址
`salt` VARCHAR(50), -- 盐
`password` VARCHAR(50), -- 密码
`mark` VARCHAR(255), -- 备注
`permission` TEXT, -- 权限
`created_user_id` INTEGER, -- 创建者编号
`created_at` DATETIME, -- 创建时间
`updated_at` DATETIME, -- 更新时间
`deleted_at` DATETIME, -- 删除时间
PRIMARY KEY(`id`)
);
CREATE TABLE "user2" ( -- 用户管理
"id" INTEGER, -- 编号
"name" VARCHAR(50), -- 名称
"email" VARCHAR(255), -- 邮箱
"address" TEXT, -- 地址
"salt" VARCHAR(50), -- 盐
"password" VARCHAR(50), -- 密码
"mark" VARCHAR(255), -- 备注
"permission" TEXT, -- 权限
"created_user_id" INTEGER, -- 创建者编号
"created_at" DATETIME, -- 创建时间
"updated_at" DATETIME, -- 更新时间
"deleted_at" DATETIME, -- 删除时间
PRIMARY KEY("id")
);
CREATE TABLE IF NOT EXISTS user3 ( -- 用户管理
id INTEGER, -- 编号
name VARCHAR(50), -- 名称
email VARCHAR(255), -- 邮箱
address TEXT, -- 地址
salt VARCHAR(50), -- 盐
password VARCHAR(50), -- 密码
mark VARCHAR(255), -- 备注
permission TEXT, -- 权限
created_user_id INTEGER, -- 创建者编号
created_at DATETIME, -- 创建时间
updated_at DATETIME, -- 更新时间
deleted_at DATETIME, -- 删除时间
PRIMARY KEY(id)
);
+105
View File
@@ -0,0 +1,105 @@
package db
import (
"context"
"fmt"
"strings"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/database/gdb"
)
// func getSQLiteSchemaByCli(tableName string, db gdb.DB) (string, error) {
// dbConf := db.GetConfig()
// cmd := exec.Command("sqlite3", dbConf.Name, fmt.Sprintf(".schema %s", tableName))
// glog.Info(context.TODO(), "sqlite3", dbConf.Name, fmt.Sprintf("'.schema %s'", tableName))
// output, err := cmd.CombinedOutput()
// if err != nil {
// return "", err
// }
// return strings.TrimSpace(string(output)), nil
// }
func getSQLiteSchemaBySql(ctx context.Context, tableName string, db gdb.DB) (string, error) {
schemaRes, err := db.GetValue(ctx, fmt.Sprintf(`SELECT sql FROM sqlite_master WHERE type='table' AND name='%s';`, tableName))
if err != nil {
return "", err
}
return schemaRes.String(), nil
}
func getSQliteTableComments(createTableSql string) (tableComment, tableName string) {
// 按照换行符分割文本
lines := strings.Split(createTableSql, "\n")
// 循环输出每一行
for _, line := range lines {
// 检查 createTableSql 是否包含 comment
if strings.Contains(line, "--") {
if strings.Contains(line, "CREATE TABLE") {
tableName = getLastWord(strings.Split(line, "(")[0])
tableComment = strings.Split(line, "--")[1]
}
}
}
return
}
func getSQliteFieldsComments(createTableSql string) (fieldCommentMap gmap.Map, tableComment, tableName string) {
// 按照换行符分割文本
lines := strings.Split(createTableSql, "\n")
// 循环输出每一行
for _, line := range lines {
// 检查 createTableSql 是否包含 comment
if strings.Contains(line, "--") {
if strings.Contains(line, "CREATE TABLE") {
tableName = getLastWord(strings.Split(line, "(")[0])
tableComment = strings.Split(line, "--")[1]
} else {
firstWord := getFirstWord(line)
lastWord := getLastWord(line)
fieldCommentMap.Set(firstWord, lastWord)
}
}
}
return
}
func transSqliteTablesComment(ctx context.Context, tableNames []string, db gdb.DB) (tables []*TableComment, err error) {
schemaStr := ""
eleIgnore := "sqlite_sequence"
for _, v := range tableNames {
if v != eleIgnore {
schemaStr, err = getSQLiteSchemaBySql(ctx, v, db)
if err != nil {
return
}
comment, _ := getSQliteTableComments(schemaStr)
tables = append(tables, &TableComment{
Name: v,
Comment: comment,
})
}
}
return
}
func fixSqliteFieldsComment(ctx context.Context, tableName string, db gdb.DB, fields map[string]*gdb.TableField) (map[string]*gdb.TableField, error) {
// 记录: db.DoSelect 无法执行 .开头的命令
// schemaRes, err := db.DoSelect(ctx, dbConf.Link, fmt.Sprintf(`.schema %s`, d.QuoteWord(table)))
// 记录: 查询 sqlite_master 不响应任何结果
// s, err := db.Query(ctx, `select * from sqlite_master WHERE name="%s";`, tableName)
// schemaStr, err := getSQLiteSchemaBySql(tableName, db)
schemaStr, err := getSQLiteSchemaBySql(ctx, tableName, db)
if err != nil {
return fields, err
}
comments, _, _ := getSQliteFieldsComments(schemaStr)
for i := range fields {
if comments.Contains(i) {
fields[i].Comment = comments.Get(i).(string)
}
}
return fields, nil
}
+74
View File
@@ -0,0 +1,74 @@
package db
import (
"hotgo/internal/consts"
"strings"
"unicode"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/text/gstr"
)
// 判断字符是否为字母、数字或下划线
func isWordChar(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
}
// 获取一行文本中的第一个完整单词
func getFirstWord(text string) string {
fields := strings.FieldsFunc(text, func(r rune) bool { return !isWordChar(r) })
if len(fields) > 0 {
return fields[0]
}
return ""
}
// 获取一行文本中的最后一个完整单词
func getLastWord(text string) string {
fields := strings.FieldsFunc(text, func(r rune) bool { return !isWordChar(r) })
if len(fields) > 0 {
return fields[len(fields)-1]
}
return ""
}
// GetQuoteChar 获取数据库对应的引号字符
// MySQL使用反引号 `,PostgreSQL使用双引号 "
func GetQuoteChar() string {
db := g.DB()
if db == nil {
return "`" // 默认MySQL
}
dbType := db.GetConfig().Type
if dbType == consts.DBPgsql {
return "\""
}
return "`"
}
// QuoteIdentifier 引用标识符(表名、字段名)
// 自动去除已有的引号,避免重复引用
func QuoteIdentifier(identifier string) string {
identifier = gstr.Trim(identifier, "`\"")
q := GetQuoteChar()
return q + identifier + q
}
// QuoteField 引用完整字段(表名.字段名)
// 自动去除表名和字段名中可能已有的引号
func QuoteField(table, field string) string {
table = gstr.Trim(table, "`\"")
field = gstr.Trim(field, "`\"")
q := GetQuoteChar()
return q + table + q + "." + q + field + q
}
// QuoteFieldAs 引用字段并添加别名(表名.字段名 as 别名)
// 自动去除表名、字段名、别名中可能已有的引号
func QuoteFieldAs(table, field, alias string) string {
table = gstr.Trim(table, "`\"")
field = gstr.Trim(field, "`\"")
alias = gstr.Trim(alias, "`\"")
q := GetQuoteChar()
return q + table + q + "." + q + field + q + " as " + q + alias + q
}
+42
View File
@@ -0,0 +1,42 @@
// Package encrypt
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package encrypt
import (
"encoding/base64"
"github.com/forgoer/openssl"
)
// AesECBEncrypt 加密
func AesECBEncrypt(src, key []byte) (dst []byte, err error) {
return openssl.AesECBEncrypt(src, key, openssl.PKCS7_PADDING)
}
// AesECBDecrypt 解密
func AesECBDecrypt(src, key []byte) (dst []byte, err error) {
return openssl.AesECBDecrypt(src, key, openssl.PKCS7_PADDING)
}
// MustAesECBEncryptToString
// Return the encryption result directly. Panic error
func MustAesECBEncryptToString(bytCipher, key string) string {
dst, err := AesECBEncrypt([]byte(bytCipher), []byte(key))
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(dst)
}
// MustAesECBDecryptToString
// Directly return decryption result, panic error
func MustAesECBDecryptToString(bytCipher, key string) string {
dst, err := AesECBDecrypt([]byte(bytCipher), []byte(key))
if err != nil {
panic(err)
}
return string(dst)
}
+29
View File
@@ -0,0 +1,29 @@
// Package encrypt
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package encrypt
import (
"crypto/md5"
"fmt"
"hash/fnv"
)
// Md5ToString 生成md5
func Md5ToString(str string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(str)))
}
// Md5 生成md5
func Md5(b []byte) string {
return fmt.Sprintf("%x", md5.Sum(b))
}
func Hash32(b []byte) uint32 {
h := fnv.New32a()
h.Write(b)
return h.Sum32()
}
+130
View File
@@ -0,0 +1,130 @@
package encrypt
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"io"
"strings"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
)
func fieldKey(ctx context.Context) ([]byte, error) {
secret := strings.TrimSpace(g.Cfg().MustGet(ctx, "security.dataKey").String())
if secret == "" {
return nil, gerror.New("敏感字段加密密钥未配置")
}
sum := sha256.Sum256([]byte(secret))
return sum[:], nil
}
// EncryptField encrypts one sensitive value with AES-256-GCM and a fresh nonce.
func EncryptField(ctx context.Context, plaintext string) (string, error) {
if plaintext == "" {
return "", nil
}
key, err := fieldKey(ctx)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", gerror.Wrap(err, "初始化敏感字段加密失败")
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", gerror.Wrap(err, "初始化敏感字段加密失败")
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", gerror.Wrap(err, "生成敏感字段随机数失败")
}
sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
return base64.RawURLEncoding.EncodeToString(sealed), nil
}
func DecryptField(ctx context.Context, encoded string) (string, error) {
if encoded == "" {
return "", nil
}
key, err := fieldKey(ctx)
if err != nil {
return "", err
}
raw, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
return "", gerror.Wrap(err, "敏感字段密文格式错误")
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
if len(raw) < gcm.NonceSize() {
return "", gerror.New("敏感字段密文不完整")
}
plain, err := gcm.Open(nil, raw[:gcm.NonceSize()], raw[gcm.NonceSize():], nil)
if err != nil {
return "", gerror.Wrap(err, "敏感字段解密失败")
}
return string(plain), nil
}
// HashField creates a deterministic, non-reversible lookup key with a secret pepper.
func HashField(ctx context.Context, value string) (string, error) {
key, err := fieldKey(ctx)
if err != nil {
return "", err
}
h := hmac.New(sha256.New, key)
_, _ = h.Write([]byte(strings.TrimSpace(value)))
return hex.EncodeToString(h.Sum(nil)), nil
}
func MaskMobile(value string) string {
value = strings.TrimSpace(value)
if len(value) < 7 {
return "***"
}
return value[:3] + "****" + value[len(value)-4:]
}
func MaskName(value string) string {
runes := []rune(strings.TrimSpace(value))
if len(runes) == 0 {
return ""
}
if len(runes) == 1 {
return "*"
}
return string(runes[0]) + strings.Repeat("*", len(runes)-1)
}
func MaskAccount(value string) string {
value = strings.TrimSpace(value)
if len(value) <= 2 {
return "****"
}
if len(value) <= 8 {
return "****" + value[len(value)-2:]
}
return value[:4] + strings.Repeat("*", len(value)-8) + value[len(value)-4:]
}
func MaskAddress(value string) string {
runes := []rune(strings.TrimSpace(value))
if len(runes) <= 6 {
return "******"
}
return string(runes[:6]) + "****"
}
+15
View File
@@ -0,0 +1,15 @@
package encrypt
import "testing"
func TestMasking(t *testing.T) {
if got := MaskMobile("13800000001"); got != "138****0001" {
t.Fatalf("mobile mask: %s", got)
}
if got := MaskName("测试会员"); got != "测***" {
t.Fatalf("name mask: %s", got)
}
if got := MaskAccount("6222020202020202001"); got != "6222***********2001" {
t.Fatalf("account mask: %s", got)
}
}
+150
View File
@@ -0,0 +1,150 @@
// Package excel
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package excel
import (
"context"
"fmt"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gconv"
"github.com/xuri/excelize/v2"
"hotgo/internal/library/contexts"
"hotgo/internal/model"
"net/url"
"reflect"
"time"
"unicode"
)
var (
// 单元格表头
char = []string{"", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
// 默认行样式
defaultRowStyle = &excelize.Style{
Font: &excelize.Font{
Color: "#666666",
Size: 13,
Family: "Arial",
},
Alignment: &excelize.Alignment{
Horizontal: "center",
Vertical: "center",
},
}
)
// ExportByStructs 导出切片结构体到excel表格
func ExportByStructs(ctx context.Context, tags []string, list interface{}, fileName string, sheetName string) (err error) {
f := excelize.NewFile()
f.SetSheetName("Sheet1", sheetName)
_ = f.SetRowHeight("Sheet1", 1, 30)
rowStyleID, _ := f.NewStyle(defaultRowStyle)
if err != nil {
return
}
_ = f.SetSheetRow(sheetName, "A1", &tags)
var (
length = len(tags)
headStyle = letter(length)
lastRow string
widthRow string
)
for k, v := range headStyle {
if k == length-1 {
lastRow = fmt.Sprintf("%s1", v)
widthRow = v
}
}
if err = f.SetColWidth(sheetName, "A", widthRow, 30); err != nil {
return err
}
var rowNum = 1
for _, v := range gconv.Interfaces(list) {
t := reflect.TypeOf(v)
value := reflect.ValueOf(v)
row := make([]interface{}, 0)
for l := 0; l < t.NumField(); l++ {
val := value.Field(l).Interface()
row = append(row, val)
}
rowNum++
if err = f.SetSheetRow(sheetName, "A"+gconv.String(rowNum), &row); err != nil {
return
}
if err = f.SetCellStyle(sheetName, fmt.Sprintf("A%d", rowNum), lastRow, rowStyleID); err != nil {
return
}
}
r := ghttp.RequestFromCtx(ctx)
if r == nil {
err = gerror.New("ctx not http request")
return
}
writer := r.Response.Writer
writer.Header().Set("Content-Type", "application/octet-stream")
writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.xlsx", url.QueryEscape(fileName)))
writer.Header().Set("Content-Transfer-Encoding", "binary")
writer.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
if err = f.Write(writer); err != nil {
return
}
// 加入到上下文
contexts.SetResponse(ctx, &model.Response{
Code: gcode.CodeOK.Code(),
Message: "export successfully!",
Timestamp: time.Now().Unix(),
TraceID: gctx.CtxId(ctx),
})
return
}
// letter 生成完整的表头
func letter(length int) []string {
var str []string
for i := 1; i <= length; i++ {
str = append(str, numToChars(i))
}
return str
}
// numToChars 将数字转换为具体的表格表头名称
func numToChars(num int) string {
var cols string
v := num
for v > 0 {
k := v % 26
if k == 0 {
k = 26
}
v = (v - k) / 26
cols = char[k] + cols
}
return cols
}
// NextLetter 传入一个字母,获取下一个字母
func NextLetter(input string) string {
if len(input) == 0 {
return ""
}
upperInput := unicode.ToUpper(rune(input[0]))
if upperInput >= 'A' && upperInput < 'Z' {
return string(upperInput + 1)
}
return "A"
}
+103
View File
@@ -0,0 +1,103 @@
// Package file
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package file
import (
"bytes"
"hotgo/utility/format"
"io"
"mime/multipart"
"os"
"path/filepath"
"github.com/gogf/gf/v2/os/gfile"
)
// 文件信息
type fileInfo struct {
name string
size int64
}
// WalkDir 递归获取目录下文件的名称和大小
func WalkDir(dirname string) (error, []fileInfo) {
op, err := filepath.Abs(dirname) // 获取目录的绝对路径
if nil != err {
return err, nil
}
files, err := os.ReadDir(op) // 获取目录下所有文件的信息,包括文件和文件夹
if nil != err {
return err, nil
}
var fileInfos []fileInfo // 返回值,存储读取的文件信息
for _, f := range files {
if f.IsDir() { // 如果是目录,那么就递归调用
err, fs := WalkDir(op + `/` + f.Name()) // 路径分隔符,linux 和 windows 不同
if nil != err {
return err, nil
}
fileInfos = append(fileInfos, fs...) // 将 slice 添加到 slice
} else {
info, err := f.Info()
if nil != err {
return err, nil
}
fi := fileInfo{op + `/` + f.Name(), info.Size()}
fileInfos = append(fileInfos, fi) // slice 中添加成员
}
}
return nil, fileInfos
}
// DirSize 获取目录下所有文件大小
func DirSize(dirname string) string {
var (
ss int64
_, files = WalkDir(dirname)
)
for _, n := range files {
ss += n.size
}
return format.FileSize(ss)
}
func MergeAbs(path string, fileName ...string) string {
var paths = []string{gfile.RealPath(path)}
paths = append(paths, fileName...)
return gfile.Join(paths...)
}
// NewMultipartFileHeader 创建一个MultipartFileHeader
func NewMultipartFileHeader(filename string, b []byte) (*multipart.FileHeader, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
return nil, err
}
if _, err = io.Copy(part, bytes.NewReader(b)); err != nil {
return nil, err
}
if err = writer.Close(); err != nil {
return nil, err
}
reader := multipart.NewReader(body, writer.Boundary())
form, err := reader.ReadForm(int64(len(b)) + 1024)
if err != nil {
return nil, err
}
defer form.RemoveAll()
if files, ok := form.File["file"]; ok && len(files) > 0 {
return files[0], nil
}
return nil, io.ErrUnexpectedEOF
}
+73
View File
@@ -0,0 +1,73 @@
// Package format
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package format
import (
"fmt"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/util/gconv"
"strconv"
)
// Round2String 四舍五入保留小数,默认2位
func Round2String(value float64, args ...interface{}) string {
var places = 2
if len(args) > 0 {
places = gconv.Int(args[0])
}
return fmt.Sprintf("%0."+strconv.Itoa(places)+"f", value)
}
// Round2Float64 四舍五入保留小数,默认2位
func Round2Float64(value float64, args ...interface{}) float64 {
return gconv.Float64(Round2String(value, args...))
}
// FileSize 字节的单位转换 保留两位小数
func FileSize(data int64) string {
var factor float64 = 1024
res := float64(data)
for _, unit := range []string{"", "K", "M", "G", "T", "P"} {
if res < factor {
return fmt.Sprintf("%.2f%sB", res, unit)
}
res /= factor
}
return fmt.Sprintf("%.2f%sB", res, "P")
}
// AgoTime 多久以前
func AgoTime(gt *gtime.Time) string {
if gt == nil {
return ""
}
n := gtime.Now().Timestamp()
t := gt.Timestamp()
var ys int64 = 31536000
var ds int64 = 86400
var hs int64 = 3600
var ms int64 = 60
var ss int64 = 1
var rs string
d := n - t
switch {
case d > ys:
rs = fmt.Sprintf("%d年前", int(d/ys))
case d > ds:
rs = fmt.Sprintf("%d天前", int(d/ds))
case d > hs:
rs = fmt.Sprintf("%d小时前", int(d/hs))
case d > ms:
rs = fmt.Sprintf("%d分钟前", int(d/ms))
case d > ss:
rs = fmt.Sprintf("%d秒前", int(d/ss))
default:
rs = "刚刚"
}
return rs
}
+56
View File
@@ -0,0 +1,56 @@
// Package simple
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package simple
import (
"context"
"sync"
)
type EventFunc func(ctx context.Context, args ...interface{})
type sEvent struct {
sync.Mutex
list map[string][]EventFunc // 所有事件的列表
}
var event *sEvent
// Event 事件实例
func Event() *sEvent {
if event == nil {
event = &sEvent{
list: make(map[string][]EventFunc),
}
}
return event
}
// Register 往一个分组中注册事件
func (e *sEvent) Register(group string, callback EventFunc) {
e.Lock()
defer e.Unlock()
e.list[group] = append(e.list[group], callback)
}
// Call 回调一个分组的事件
func (e *sEvent) Call(group string, ctx context.Context, args ...interface{}) {
if events, ok := e.list[group]; ok {
for _, f := range events {
f(ctx, args...)
}
}
}
// Remove 移动一个分组的事件
func (e *sEvent) Remove(group string) {
delete(e.list, group)
}
// Clear 清空事件列表
func (e *sEvent) Clear() {
e.list = make(map[string][]EventFunc)
}
+144
View File
@@ -0,0 +1,144 @@
// Package simple
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2025 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package simple
import (
"context"
"github.com/gogf/gf/v2/crypto/gmd5"
"github.com/gogf/gf/v2/encoding/gbase64"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/glog"
"hotgo/internal/consts"
"hotgo/utility/encrypt"
)
// RouterPrefix 获取应用路由前缀
func RouterPrefix(ctx context.Context, app string) string {
return g.Cfg().MustGet(ctx, "router."+app+".prefix", "/"+app+"").String()
}
// FilterMaskDemo 过滤演示环境下的配置隐藏字段
func FilterMaskDemo(ctx context.Context, src g.Map) g.Map {
if src == nil {
return nil
}
if !IsDemo(ctx) {
return src
}
for k := range src {
if _, ok := consts.ConfigMaskDemoField[k]; ok {
src[k] = consts.DemoTips
}
}
return src
}
// DefaultErrorTplContent 获取默认的错误模板内容
func DefaultErrorTplContent(ctx context.Context) string {
return gfile.GetContents(g.Cfg().MustGet(ctx, "viewer.paths").String() + "/error/default.html")
}
// DecryptText 解密文本
func DecryptText(text string) (string, error) {
str, err := gbase64.Decode([]byte(text))
if err != nil {
return "", err
}
str, err = encrypt.AesECBDecrypt(str, consts.RequestEncryptKey)
if err != nil {
return "", err
}
return string(str), nil
}
// CheckPassword 检查密码
func CheckPassword(input, salt, hash string) (err error) {
// 解密密码
password, err := DecryptText(input)
if err != nil {
return err
}
if hash != gmd5.MustEncryptString(password+salt) {
err = gerror.New("用户名或密码错误")
return
}
return
}
// GetHeaderLocale 获取请求头语言设置
// gf支持格式:en/ja/ru/zh-CN/zh-TW
func GetHeaderLocale(ctx context.Context) (lang string) {
lang = g.Cfg().MustGet(ctx, "system.i18n.defaultLanguage", consts.SysDefaultLanguage).String()
// 没有开启国际化,使用默认语言
if !g.Cfg().MustGet(ctx, "system.i18n.switch", true).Bool() {
return
}
r := ghttp.RequestFromCtx(ctx)
if r == nil {
return
}
locale := r.Header.Get("Locale")
// 简体中文
if locale == "zh-CN" || locale == "zh-Hans" || locale == "zh" || locale == "ZH" {
lang = "zh-CN"
return
}
// 繁体
if locale == "zh-TW" || locale == "zh-Hant" {
lang = "zh-TW"
return
}
// 英文
if locale == "en" || locale == "EN" {
lang = "en"
return
}
// 更多语言
// ...
return
}
// SafeGo 安全的调用协程,遇到错误时输出错误日志而不是抛出panic
func SafeGo(ctx context.Context, f func(ctx context.Context), lv ...int) {
g.Go(ctx, f, func(ctx context.Context, err error) {
var level = glog.LEVEL_ERRO
if len(lv) > 0 {
level = lv[0]
}
Logf(level, ctx, "SafeGo exec failed:%+v", err)
})
}
func Logf(level int, ctx context.Context, format string, v ...interface{}) {
switch level {
case glog.LEVEL_DEBU:
g.Log().Debugf(ctx, format, v...)
case glog.LEVEL_INFO:
g.Log().Infof(ctx, format, v...)
case glog.LEVEL_NOTI:
g.Log().Noticef(ctx, format, v...)
case glog.LEVEL_WARN:
g.Log().Warningf(ctx, format, v...)
case glog.LEVEL_ERRO:
g.Log().Errorf(ctx, format, v...)
case glog.LEVEL_CRIT:
g.Log().Criticalf(ctx, format, v...)
case glog.LEVEL_PANI:
g.Log().Panicf(ctx, format, v...)
case glog.LEVEL_FATA:
g.Log().Fatalf(ctx, format, v...)
default:
g.Log().Errorf(ctx, format, v...)
}
}
+31
View File
@@ -0,0 +1,31 @@
// Package simple
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2024 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package simple
import (
"context"
"github.com/gogf/gf/v2/frame/g"
)
// AppName 应用名称
func AppName(ctx context.Context) string {
return g.Cfg().MustGet(ctx, "system.appName", "hotgo").String()
}
// Debug debug
func Debug(ctx context.Context) bool {
return g.Cfg().MustGet(ctx, "system.debug", true).Bool()
}
// IsDemo 是否为演示系统
func IsDemo(ctx context.Context) bool {
return g.Cfg().MustGet(ctx, "system.isDemo", true).Bool()
}
// IsCluster 是否为集群部署
func IsCluster(ctx context.Context) bool {
return g.Cfg().MustGet(ctx, "system.isCluster", true).Bool()
}
+108
View File
@@ -0,0 +1,108 @@
// Package tree
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package tree
import (
"fmt"
"github.com/gogf/gf/v2/util/gconv"
"strings"
)
const (
treeDefaultId = "id" // 树ID
treeDefaultPid = "pid" // 上级树ID
treeDefaultChildren = "children" // 下级属性
treeBeginCut = "tr_" // 树标识开头
treeEndCut = " " // 树标识结尾
)
// GenOption 生成选项
type GenOption struct {
IdField string
PidField string
ChildrenField string
}
// GenLabel 生成关系树标识
func GenLabel(basic string, appendId int64) string {
return fmt.Sprintf("%v%v%v%v", basic, treeBeginCut, appendId, treeEndCut)
}
// GetIdLabel 获取指定Id的树标签
func GetIdLabel(id int64) string {
return fmt.Sprintf("%v%v%v", treeBeginCut, id, treeEndCut)
}
// GetIds 获取上级ID集合
func GetIds(tree string) (ids []int64) {
idsStr := strings.Split(tree, treeEndCut)
if len(idsStr) == 0 {
return
}
for _, v := range idsStr {
newId := gconv.Int64(strings.ReplaceAll(v, treeBeginCut, ""))
if newId > 0 {
ids = append(ids, newId)
}
}
return
}
// GenTree 生成关系树
func GenTree(menus []map[string]interface{}) (realMenu []map[string]interface{}) {
return GenTreeWithField(menus, GenOption{
IdField: treeDefaultId,
PidField: treeDefaultPid,
ChildrenField: treeDefaultChildren,
})
}
// GenTreeWithField 生成关系树 自定义生成属性
func GenTreeWithField(menus []map[string]interface{}, op GenOption) (realMenu []map[string]interface{}) {
if len(menus) < 1 {
return
}
minPid := GetMinPid(menus, op.PidField)
formatMenu := make(map[int]map[string]interface{})
for _, m := range menus {
formatMenu[gconv.Int(m[op.IdField])] = m
if gconv.Int(m[op.PidField]) == minPid {
realMenu = append(realMenu, m) // 需要返回的顶级菜单
}
}
// 得益于都是地址操作,可以直接往父级塞
for _, m := range formatMenu {
if formatMenu[gconv.Int(m[op.PidField])] == nil {
continue
}
if formatMenu[gconv.Int(m[op.PidField])][op.ChildrenField] == nil {
formatMenu[gconv.Int(m[op.PidField])][op.ChildrenField] = []map[string]interface{}{}
}
formatMenu[gconv.Int(m[op.PidField])][op.ChildrenField] = append(formatMenu[gconv.Int(m[op.PidField])][op.ChildrenField].([]map[string]interface{}), m)
}
return
}
func GetMinPid(menus []map[string]interface{}, pidField string) int {
index := -1
for _, m := range menus {
if index == -1 {
index = gconv.Int(m[pidField])
continue
}
if gconv.Int(m[pidField]) < index {
index = gconv.Int(m[pidField])
}
}
if index == -1 {
return 0
}
return index
}
+35
View File
@@ -0,0 +1,35 @@
// Package tree
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2024 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package tree
type Node interface {
ID() int64 // 获取节点ID
PID() int64 // 获取父级节点ID
SetChildren(children []Node) // 设置子节点数据
}
// ListToTree 根据上下级关系将列表数据转为树状数据
func ListToTree(pid int64, nodes []Node) (list []Node, err error) {
if len(nodes) == 0 {
return nodes, nil
}
for _, v := range nodes {
if v.PID() == pid {
item := v
// 递归添加子节点
child, err := ListToTree(v.ID(), nodes)
if err != nil {
return nil, err
}
if len(child) > 0 {
item.SetChildren(child)
}
list = append(list, item)
}
}
return
}
+74
View File
@@ -0,0 +1,74 @@
// Package url
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package url
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/utility/validate"
"strings"
)
// UriToMap 将URL参数转为map
func UriToMap(uri string) g.MapStrStr {
m := make(map[string]string)
if len(uri) < 1 {
return nil
}
if uri[0:1] == "?" {
uri = uri[1:]
}
pars := strings.Split(uri, "&")
for _, par := range pars {
kv := strings.Split(par, "=")
m[kv[0]] = kv[1]
}
return m
}
// MapToUri 将map转为URL参数
func MapToUri(params g.MapStrStr) string {
escape := ""
for k, v := range params {
if escape != "" {
escape = escape + "&"
}
escape = escape + k + "=" + v
}
return escape
}
// GetAddr 获取请求中的请求地址,协议+域名/IP:端口
func GetAddr(ctx context.Context) string {
r := ghttp.RequestFromCtx(ctx)
if r == nil {
return ""
}
var (
scheme = "http"
proto = r.Header.Get("X-Forwarded-Proto")
)
if r.TLS != nil || gstr.Equal(proto, "https") {
scheme = "https"
}
return fmt.Sprintf(`%s://%s`, scheme, r.Host)
}
// GetDomain 获取请求中的域名,如果请求不是域名则返回空
func GetDomain(ctx context.Context) string {
r := ghttp.RequestFromCtx(ctx)
if r == nil {
g.Log().Info(ctx, "GetDomain ctx not request")
return ""
}
if validate.IsDNSName(r.Host) {
return r.Host
}
return ""
}
+129
View File
@@ -0,0 +1,129 @@
// Package useragent
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package useragent
import (
"fmt"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/internal/consts"
"regexp"
"strings"
)
// GetOs 获取OS名称
func GetOs(userAgent string) string {
osName := consts.Unknown
if userAgent == "" {
return osName
}
var (
strRe, _ = regexp.Compile(`(?i:\((.*?)\))`)
levelNames = ":micromessenger:dart:Windows NT:Windows Mobile:Windows Phone:Windows Phone OS:Macintosh|Macintosh:Mac OS:CrOS|CrOS:iPhone OS:iPad|iPad:OS:Android:Linux:blackberry:hpwOS:Series:Symbian:PalmOS:SymbianOS:J2ME:Sailfish:Bada:MeeGo:webOS|hpwOS:Maemo:"
namesArr = strings.Split(strings.Trim(levelNames, ":"), ":")
regStrArr = make([]string, len(namesArr))
)
for k, name := range namesArr {
regStrArr[k] = fmt.Sprintf("(%s[\\s?\\/XxSs0-9_.]+)", name)
}
userAgent = strRe.FindString(userAgent)
var (
nameRe, _ = regexp.Compile(fmt.Sprintf("(?i:%s)", strings.Join(regStrArr, "|")))
names = nameRe.FindAllString(userAgent, -1)
name = ""
)
for _, s := range names {
if len(name) == 0 {
name = strings.TrimSpace(s)
} else {
if strings.Contains(name, "Macintosh") && s != "" {
name = strings.TrimSpace(s)
} else if strings.Contains(name, s) {
name = strings.TrimSpace(s)
} else if !strings.Contains(s, name) {
if strings.Contains(name, "iPhone") || strings.Contains(name, "iPad") {
s = gstr.Trim(s, "Mac OS X")
}
if s != "" {
name += " " + strings.TrimSpace(s)
}
}
break
}
if strings.Contains(name, "Windows NT") {
name = getWinOsNameWithWinNT(name)
break
}
}
if name != "" {
osName = name
}
return osName
}
// GetBrowser 获取浏览器名称
func GetBrowser(userAgent string) string {
var (
deviceName = consts.Unknown
levelNames = ":VivoBrowser:QQDownload:QQBrowser:QQ:MQQBrowser:MicroMessenger:TencentTraveler:LBBROWSER:TaoBrowser:BrowserNG:UCWEB:TwonkyBeamBrowser:NokiaBrowser:OviBrowser:NF-Browser:OneBrowser:Obigo:DiigoBrowser:baidubrowser:baiduboxapp:xiaomi:Redmi:MI:Lumia:Micromax:MSIEMobile:IEMobile:EdgiOS:Yandex:Mercury:Openwave:TouchPad:UBrowser:Presto:Maxthon:MetaSr:Trident:Opera:IEMobile:Edge:Chrome:Chromium:OPR:CriOS:Firefox:FxiOS:fennec:CrMo:Safari:Nexus One:Nexus S:Nexus:Blazer:teashark:bolt:HTC:Dell:Motorola:Samsung:LG:Sony:SonyST:SonyLT:SonyEricsson:Asus:Palm:Vertu:Pantech:Fly:Wiko:i-mobile:Alcatel:Nintendo:Amoi:INQ:ONEPLUS:Tapatalk:PDA:Novarra-Vision:NetFront:Minimo:FlyFlow:Dolfin:Nokia:Series:AppleWebKit:Mobile:Mozilla:Version:"
namesArr = strings.Split(strings.Trim(levelNames, ":"), ":")
regStrArr []string
)
for _, name := range namesArr {
regStrArr = append(regStrArr, fmt.Sprintf("(%s[\\s?\\/0-9.]+)", name))
}
var (
regexpStr = fmt.Sprintf("(?i:%s)", strings.Join(regStrArr, "|"))
nameRe, _ = regexp.Compile(regexpStr)
names = nameRe.FindAllString(userAgent, -1)
level = 0
)
for _, name := range names {
replaceRe, _ := regexp.Compile(`(?i:[\s?\/0-9.]+)`)
l := strings.Index(levelNames, fmt.Sprintf(":%s:", replaceRe.ReplaceAllString(name, "")))
if level == 0 {
deviceName = strings.TrimSpace(name)
}
if l >= 0 && (level == 0 || level > l) {
level = l
deviceName = strings.TrimSpace(name)
}
}
return deviceName
}
func getWinOsNameWithWinNT(sName string) string {
osName := "Windows"
types := map[string]string{
"Windows NT 10": "Windows 10",
"Windows NT 6.3": "Windows 8",
"Windows NT 6.2": "Windows 8",
"Windows NT 6.1": "Windows 7",
"Windows NT 6.0": "Windows Vista/Server 2008",
"Windows NT 5.2": "Windows Server 2003",
"Windows NT 5.1": "Windows XP",
"Windows NT 5": "Windows 2000",
"Windows NT 4": "Windows NT4",
}
for keyWord, name := range types {
if strings.Contains(sName, keyWord) {
osName = name
break
}
}
return osName
}
+32
View File
@@ -0,0 +1,32 @@
// Package validate
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package validate
import (
"context"
"github.com/gogf/gf/v2/frame/g"
)
// Filter 通用过滤器
// Filter 预处理和数据过滤接口,目前主要用于input层的输入过滤和内部效验。
// 你可以在任意地方使用它,只要实现了Filter接口即可
type Filter interface {
// Filter gf效验规则 https://goframe.org/pages/viewpage.action?pageId=1114367
Filter(ctx context.Context) error
}
// PreFilter 预过滤
func PreFilter(ctx context.Context, in interface{}) error {
return g.Try(ctx, func(ctx context.Context) {
if c, ok := in.(Filter); ok {
if err := c.Filter(ctx); err != nil {
g.Throw(err)
}
return
}
})
}
+72
View File
@@ -0,0 +1,72 @@
// Package validate_test
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package validate_test
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/test/gtest"
"hotgo/utility/validate"
"testing"
)
// MockFilter 是 Filter 接口的模拟实现。
type MockFilter struct {
Foo string
Bar int
}
func (f *MockFilter) Filter(ctx context.Context) error {
// 模拟过滤逻辑
// 过滤出错的例子
if f.Foo == "" {
return gerror.New("Foo 字段是必需的")
}
// 过滤操作的例子
f.Bar += 10
return nil
}
func TestPreFilter(t *testing.T) {
ctx := context.Background()
input := &MockFilter{
Foo: "test",
Bar: 5,
}
err := validate.PreFilter(ctx, input)
gtest.C(t, func(t *gtest.T) {
t.AssertNil(err)
})
t.Logf("input:%+v", input)
// 验证过滤结果
expectedBar := 15
gtest.C(t, func(t *gtest.T) {
t.Assert(input.Bar, expectedBar)
})
}
func TestPreFilter_Error(t *testing.T) {
ctx := context.Background()
input := &MockFilter{
Foo: "",
Bar: 5,
}
err := validate.PreFilter(ctx, input)
gtest.C(t, func(t *gtest.T) {
t.AssertNE(err, nil)
})
expectedError := "Foo 字段是必需的"
gtest.C(t, func(t *gtest.T) {
t.Assert(err.Error(), expectedError)
})
}
+38
View File
@@ -0,0 +1,38 @@
// Package validate
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package validate
import (
"github.com/gogf/gf/v2/util/gconv"
)
// 包含判断
// InSliceExistStr 判断字符或切片字符是否存在指定字符
func InSliceExistStr(elems any, search string) bool {
switch elems.(type) {
case []string:
elem := gconv.Strings(elems)
for i := 0; i < len(elem); i++ {
if gconv.String(elem[i]) == search {
return true
}
}
default:
return gconv.String(elems) == search
}
return false
}
// InSlice 元素是否存在于切片中
func InSlice[K comparable](slice []K, key K) bool {
for _, v := range slice {
if v == key {
return true
}
}
return false
}
+192
View File
@@ -0,0 +1,192 @@
// Package validate
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package validate
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/text/gstr"
"net"
"net/url"
"regexp"
"strings"
"time"
)
// 是否判断
// IsDNSName 是否是域名地址
func IsDNSName(s string) bool {
DNSName := `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
rxDNSName := regexp.MustCompile(DNSName)
return s != "" && rxDNSName.MatchString(s)
}
// IsHTTPS 是否是https请求
func IsHTTPS(ctx context.Context) bool {
r := ghttp.RequestFromCtx(ctx)
if r == nil {
g.Log().Info(ctx, "IsHTTPS ctx not request")
return false
}
return r.TLS != nil || gstr.Equal(r.Header.Get("X-Forwarded-Proto"), "https")
}
// IsIp 是否为ipv4
func IsIp(ip string) bool {
return net.ParseIP(ip) != nil
}
// IsPublicIp 是否是公网IP
func IsPublicIp(ip string) bool {
i := net.ParseIP(ip)
if i.IsLoopback() || i.IsPrivate() || i.IsMulticast() || i.IsUnspecified() || i.IsLinkLocalUnicast() || i.IsLinkLocalMulticast() {
return false
}
if ip4 := i.To4(); ip4 != nil {
return !i.Equal(net.IPv4bcast)
}
return true
}
// IsLocalIPAddr 检测 IP 地址字符串是否是内网地址
func IsLocalIPAddr(ip string) bool {
if "localhost" == ip {
return true
}
return HasLocalIP(net.ParseIP(ip))
}
// HasLocalIP 检测 IP 地址是否是内网地址
func HasLocalIP(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
ip4 := ip.To4()
if ip4 == nil {
return false
}
return ip4[0] == 10 || // 10.0.0.0/8
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) || // 172.16.0.0/12
(ip4[0] == 169 && ip4[1] == 254) || // 169.254.0.0/16
(ip4[0] == 192 && ip4[1] == 168) // 192.168.0.0/16
}
// IsMobile 是否为手机号码
func IsMobile(mobile string) bool {
pattern := `^(1[2|3|4|5|6|7|8|9][0-9]\d{4,8})$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(mobile)
}
// IsEmail 是否为邮箱地址
func IsEmail(email string) bool {
// pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z].){1,4}[a-z]{2,4}$` //匹配电子邮箱
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(email)
}
// IsURL 是否是url地址
func IsURL(u string) bool {
_, err := url.ParseRequestURI(u)
if err != nil {
return false
}
URL, err := url.Parse(u)
if err != nil || URL.Scheme == "" || URL.Host == "" {
return false
}
return true
}
// IsIDCard 是否为身份证
func IsIDCard(idCard string) bool {
sz := len(idCard)
if sz != 18 {
return false
}
weight := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
validate := []byte{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}
sum := 0
for i := 0; i < len(weight); i++ {
sum += weight[i] * int(byte(idCard[i])-'0')
}
m := sum % 11
return validate[m] == idCard[sz-1]
}
// IsSameDay 是否为同一天
func IsSameDay(t1, t2 int64) bool {
y1, m1, d1 := time.Unix(t1, 0).Date()
y2, m2, d2 := time.Unix(t2, 0).Date()
return y1 == y2 && m1 == m2 && d1 == d2
}
// IsSameMinute 是否为同一分钟
func IsSameMinute(t1, t2 int64) bool {
d1 := time.Unix(t1, 0).Format("2006-01-02 15:04")
d2 := time.Unix(t2, 0).Format("2006-01-02 15:04")
return d1 == d2
}
// IsMobileVisit 是否为移动端访问
func IsMobileVisit(userAgent string) bool {
if len(userAgent) == 0 {
return false
}
is := false
mobileKeywords := []string{"Mobile", "Android", "Silk/", "Kindle", "BlackBerry", "Opera Mini", "Opera Mobi"}
for i := 0; i < len(mobileKeywords); i++ {
if strings.Contains(userAgent, mobileKeywords[i]) {
is = true
break
}
}
return is
}
// IsWxBrowserVisit 是否为微信访问
func IsWxBrowserVisit(userAgent string) bool {
if len(userAgent) == 0 {
return false
}
is := false
userAgent = strings.ToLower(userAgent)
mobileKeywords := []string{"MicroMessenger"}
for i := 0; i < len(mobileKeywords); i++ {
if strings.Contains(userAgent, strings.ToLower(mobileKeywords[i])) {
is = true
break
}
}
return is
}
// IsWxMiniProgramVisit 是否为微信小程序访问
func IsWxMiniProgramVisit(userAgent string) bool {
if len(userAgent) == 0 {
return false
}
is := false
userAgent = strings.ToLower(userAgent)
mobileKeywords := []string{"miniProgram"}
for i := 0; i < len(mobileKeywords); i++ {
if strings.Contains(userAgent, strings.ToLower(mobileKeywords[i])) {
is = true
break
}
}
return is
}
+17
View File
@@ -0,0 +1,17 @@
// Package validate_test
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
package validate_test
import (
"github.com/gogf/gf/v2/test/gtest"
"hotgo/utility/validate"
"testing"
)
func TestIsEmail(t *testing.T) {
b := validate.IsEmail("QTT123456@163.com")
gtest.Assert(true, b)
}