This commit is contained in:
2024-06-19 14:30:11 +08:00
parent 9a9f3b71ff
commit 737c0eb28f
64 changed files with 3925 additions and 1 deletions
+51
View File
@@ -0,0 +1,51 @@
package utils
import (
"github.com/mojocn/base64Captcha"
"image/color"
"time"
)
// GenerateCaptcha 生成验证码-base64
func GenerateCaptcha() (id, b64s string, err error) {
var driver *base64Captcha.DriverString
// 配置验证码的参数
driverString := &base64Captcha.DriverString{
Height: 40,
Width: 100,
NoiseCount: 0,
ShowLineOptions: 0,
Length: 4,
Source: "1234567890",
BgColor: &color.RGBA{R: 3, G: 102, B: 214, A: 125},
Fonts: []string{"wqy-microhei.ttc"},
}
// ConvertFonts 按名称加载字体
driver = driverString.ConvertFonts()
base64Captcha.Expiration = 30 * time.Minute
store := base64Captcha.DefaultMemStore
captcha := base64Captcha.NewCaptcha(driver, store)
id, b64s, _, err = captcha.Generate()
if err != nil {
return "", "", err
}
return id, b64s, nil
}
// VerifyCaptcha 验证验证码
func VerifyCaptcha(id, answer string) bool {
// 创建验证码实例
base64Captcha.Expiration = 30 * time.Minute
store := base64Captcha.DefaultMemStore
captcha := base64Captcha.NewCaptcha(nil, store)
// 验证验证码
isValid := captcha.Verify(id, answer, true)
if !isValid {
return false
}
return true
}
+85
View File
@@ -0,0 +1,85 @@
package utils
import (
"fmt"
"github.com/gen2brain/go-fitz"
"image/jpeg"
"os"
"path/filepath"
)
// 一些计算
// ComputeIndividualIncomeTax 计算个人所得税
func ComputeIndividualIncomeTax(income float64) float64 {
if income <= 800 {
return 0
}
if income <= 4000 {
income = income - 800
}
// 实际纳税金额
if income > 4000 {
income = income * 0.8
}
// 税率、速算扣除数
var taxRate, quickDeduction float64
if income <= 20000 {
taxRate = 0.2
quickDeduction = 0
} else if income <= 50000 {
taxRate = 0.3
quickDeduction = 2000
} else {
taxRate = 0.4
quickDeduction = 7000
}
incomeTax := income*taxRate - quickDeduction
return incomeTax
}
// ConvertPDFToImages converts a PDF file to images and saves them in the specified output directory.
func ConvertPDFToImages(pdfPath string, outputDir string, filename string) error {
// Open the PDF file
doc, err := fitz.New(pdfPath)
if err != nil {
return fmt.Errorf("failed to open PDF file: %v", err)
}
defer doc.Close()
// Ensure the output directory exists
if err := os.MkdirAll(outputDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create output directory: %v", err)
}
// Iterate over each page in the PDF
for i := 0; i < doc.NumPage(); i++ {
// Render the page to an image
img, err := doc.Image(i)
if err != nil {
return fmt.Errorf("failed to render page %d: %v", i, err)
}
// Create the output file
outputFile := filepath.Join(outputDir, filename)
file, err := os.Create(outputFile)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer file.Close()
// Encode the image as JPEG and save it to the file
opts := &jpeg.Options{Quality: 80}
if err := jpeg.Encode(file, img, opts); err != nil {
return fmt.Errorf("failed to encode image: %v", err)
}
}
return nil
}
+21
View File
@@ -0,0 +1,21 @@
package utils
import (
"errors"
"os"
)
// PathExists 文件是否存在
func PathExists(path string) (bool, error) {
fi, err := os.Stat(path)
if err == nil {
if fi.IsDir() {
return true, nil
}
return false, errors.New("存在同名文件")
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
+298
View File
@@ -0,0 +1,298 @@
package utils
import (
"bytes"
"fmt"
"github.com/xuri/excelize/v2"
"reflect"
"strconv"
)
// func Export(widths []int) (bool, error) {
// f := excelize.NewFile()
// defer func() {
// _ = f.Close()
// }()
//
// // 创建一个工作表
// index, err := f.NewSheet("Sheet1")
// if err != nil {
// return false, err
// }
//
// // 设置工作簿的默认工作表
// f.SetActiveSheet(index)
//
// // 单元格对齐样式
// alignment := &excelize.Alignment{
// Horizontal: "center",
// Vertical: "center",
// }
//
// // 单元格颜色填充样式
// fill := excelize.Fill{
// Type: "pattern",
// Pattern: 1,
// Color: []string{"#c9daf8"},
// Shading: 0,
// }
//
// // 第一行的左、右、下边框
// border := []excelize.Border{
// {
// Type: "left,right,bottom",
// Color: "",
// Style: 1,
// },
// }
//
// // 工作表样式
// style, err := f.NewStyle(
// &excelize.Style{
// Fill: fill,
// Alignment: alignment,
// Border: border,
// },
// )
// if err != nil {
// return false, err
// }
//
// // 依次设置每一列的列宽
// widths = []int{18, 18, 18, 18, 18, 20, 23, 46, 18, 30, 30, 18, 18, 30, 18, 30}
// for col, width := range widths {
// // 获取列名
// colName, err := excelize.ColumnNumberToName(col + 1)
// if err != nil {
// return false, err
// }
//
// // 设置列宽
// err = f.SetColWidth("Sheet1", colName, colName, float64(width))
// if err != nil {
// return false, err
// }
//
// // 设置列背景颜色
// err = f.SetCellStyle("Sheet1", colName+"1", colName+"1", style)
// if err != nil {
// return false, err
// }
// }
//
// // 设置行高
// err = f.SetRowStyle("Sheet1", 1, 10, style)
// if err != nil {
// return false, err
// }
//
// if err := f.SaveAs("output.xlsx"); err != nil {
// return false, err
// }
//
// return true, nil
// }
// HeaderCellData 表头内容
type HeaderCellData struct {
Value string // 值
CellType string // 类型
NumberFmt string // 格式化方式
ColWidth int // 列宽
}
func Export(header []HeaderCellData, data []interface{}) (*bytes.Buffer, error) {
sheetName := "Sheet1"
f := excelize.NewFile()
defer func() {
_ = f.Close()
}()
// 创建一个工作表
index, err := f.NewSheet(sheetName)
if err != nil {
return nil, err
}
// 设置工作簿的默认工作表
f.SetActiveSheet(index)
// 设置工作表默认字体
err = f.SetDefaultFont("宋体")
if err != nil {
return nil, err
}
// 统一单元格对齐样式
alignment := &excelize.Alignment{
Horizontal: "center",
Vertical: "center",
}
// 设置行高 35-第一行
err = f.SetRowHeight(sheetName, 1, 35)
if err != nil {
return nil, err
}
// 处理工作表表头
for c, cell := range header {
// 获取列名
colName, err := excelize.ColumnNumberToName(c + 1)
if err != nil {
return nil, err
}
// 添加单元格的值
err = f.SetCellValue(sheetName, colName+"1", cell.Value)
if err != nil {
return nil, err
}
// 单元格颜色填充样式
fill := excelize.Fill{
Type: "pattern",
Pattern: 1,
Color: []string{"#c9daf8"},
Shading: 0,
}
// 第一行的左、右、下边框
border := []excelize.Border{
{
Type: "left",
Color: "#000000",
Style: 1,
},
{
Type: "right",
Color: "#000000",
Style: 1,
},
{
Type: "bottom",
Color: "#000000",
Style: 1,
},
}
// 设置单元格值类型和格式
style, _ := f.NewStyle(&excelize.Style{
Alignment: alignment, // 字体居中
Fill: fill, // 背景颜色
Border: border, // 边框
})
err = f.SetCellStyle(sheetName, colName+"1", colName+"1", style)
if err != nil {
return nil, err
}
// 设置列宽
err = f.SetColWidth(sheetName, colName, colName, float64(cell.ColWidth))
if err != nil {
return nil, err
}
}
// 设置单元格格式
row := len(data)
for i, cell := range header {
// 获取列名
colName, err := excelize.ColumnNumberToName(i + 1)
if err != nil {
return nil, err
}
// 字体居中
style := &excelize.Style{}
style = &excelize.Style{
Alignment: alignment,
}
if cell.CellType == "float" {
style.NumFmt = 2
customNumFmt := "0.000"
style.CustomNumFmt = &customNumFmt
}
if cell.CellType == "date" {
style.NumFmt = 22
customNumFmt := "yyyy-mm-dd hh:mm:ss"
style.CustomNumFmt = &customNumFmt
}
newStyle, _ := f.NewStyle(style)
err = f.SetCellStyle(sheetName, colName+"2", colName+strconv.Itoa(row), newStyle)
if err != nil {
return nil, err
}
}
// 填充数据
for r, rowData := range data {
rv := reflect.ValueOf(rowData)
for c := 0; c < rv.NumField(); c++ {
cellValue := rv.Field(c).Interface()
// 获取列名
colName, err := excelize.ColumnNumberToName(c + 1)
if err != nil {
return nil, err
}
axis := colName + fmt.Sprintf("%d", r+2)
// 设置单元格值
err = f.SetCellValue(sheetName, axis, cellValue)
if err != nil {
return nil, err
}
// 设置单元格值类型
cellType := header[c].CellType
// 字体居中
style := &excelize.Style{}
style = &excelize.Style{
Alignment: alignment,
}
if cellType == "float" {
style.NumFmt = 2
customNumFmt := "0.000"
style.CustomNumFmt = &customNumFmt
}
if cellType == "date" {
style.NumFmt = 22
customNumFmt := "yyyy-mm-dd hh:mm:ss"
style.CustomNumFmt = &customNumFmt
}
newStyle, _ := f.NewStyle(style)
err = f.SetCellStyle(sheetName, axis, axis, newStyle)
if err != nil {
return nil, err
}
// 设置行高 35-第一行
err = f.SetRowHeight(sheetName, r+2, 35)
if err != nil {
return nil, err
}
}
}
buffer, err := f.WriteToBuffer()
if err != nil {
return nil, err
}
return buffer, nil
// 保存文件
// if err := f.SaveAs("output.xlsx"); err != nil {
// return nil, err
// }
// return nil, errors.New("已导出文件")
}
+124
View File
@@ -0,0 +1,124 @@
// Package utils 身份证处理
package utils
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// GetCardAge 获取身份证年龄
func GetCardAge(cardNum string) (int, error) {
// 获取当前时间
now := time.Now()
// 解析身份证号中的出生日期
birthDateStr := cardNum[6:14]
birthYear, err := strconv.Atoi(birthDateStr[0:4])
if err != nil {
return 0, err
}
birthMonth, err := strconv.Atoi(birthDateStr[4:6])
if err != nil {
return 0, err
}
// 计算年龄
age := now.Year() - birthYear
if now.Month() < time.Month(birthMonth) {
age--
}
return age, nil
}
// CheckCardNum 检测身份证号
func CheckCardNum(cardNum string) (bool, error) {
fmt.Println(cardNum)
regex := `^(?:1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5])\d{4}(?:1[89]|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dxX]$`
match, err := regexp.MatchString(regex, cardNum)
fmt.Println(match)
if !match || err != nil {
return false, errors.New("身份证号错误")
}
return true, nil
}
// GetCardSex 获取身份证性别
func GetCardSex(cardNum string) (int, error) {
genderStr := cardNum[len(cardNum)-2 : len(cardNum)-1]
genderNum, err := strconv.Atoi(genderStr)
if err != nil {
return 0, err
}
// 判断性别
if genderNum%2 == 0 {
return 2, nil
} else {
return 1, nil
}
}
// GetMaskCardNum 身份证号码脱敏
func GetMaskCardNum(cardNum string) string {
if len(cardNum) != 18 {
return cardNum
}
// 获取身份证号前后部分
frontPart := cardNum[0:6]
backPart := cardNum[14:]
// 替换中间部分数字为 *
middlePart := "****"
// 拼接新的身份证号
maskedIDCard := frontPart + middlePart + backPart
return maskedIDCard
}
// GetMaskCardName 身份证名字脱敏
func GetMaskCardName(cardName string) string {
// 判断姓名长度
length := utf8.RuneCountInString(cardName)
// 判断是否是英文姓名
isEnglish := strings.ContainsAny(cardName, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if length == 2 {
// 两个字符的姓名
if isEnglish {
// 英文姓名
return string(cardName[0]) + "*"
} else {
// 中文姓名
return string([]rune(cardName)[0]) + "*"
}
} else if length == 3 {
// 三个字符的姓名
if isEnglish {
// 英文姓名
return string(cardName[0]) + "*" + string(cardName[2])
} else {
// 中文姓名
return string([]rune(cardName)[0]) + "*" + string([]rune(cardName)[2])
}
} else if length >= 4 {
// 四个及以上字符的姓名
if isEnglish {
// 英文姓名
return string(cardName[0]) + "*" + string(cardName[length-1])
} else {
// 中文姓名
return string([]rune(cardName)[0]) + "*" + string([]rune(cardName)[length-1])
}
}
return cardName
}
+3
View File
@@ -0,0 +1,3 @@
package utils
// int转字符串
+40
View File
@@ -0,0 +1,40 @@
package utils
import (
"github.com/golang-jwt/jwt/v5"
"knowledge/config"
"time"
)
type Token struct {
UserId string `json:"user_id"` // 用户id
jwt.RegisteredClaims // v5版本新加的方法
}
// NewJWT GenerateJWT 生成JWT
func (t Token) NewJWT() (string, error) {
ttl := time.Duration(config.C.Jwt.Ttl)
t.RegisteredClaims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(ttl * time.Hour)) // 过期时间24小时
t.RegisteredClaims.IssuedAt = jwt.NewNumericDate(time.Now()) // 签发时间
t.RegisteredClaims.NotBefore = jwt.NewNumericDate(time.Now()) // 生效时间
// 使用HS256签名算法
token := jwt.NewWithClaims(jwt.SigningMethodHS256, t)
s, err := token.SignedString([]byte(config.C.Jwt.SignKey))
return s, err
}
// ParseJwt 解析JWT
func ParseJwt(authorization string) (*Token, error) {
t, err := jwt.ParseWithClaims(authorization, &Token{}, func(token *jwt.Token) (interface{}, error) {
return []byte(config.C.Jwt.SignKey), nil
})
if claims, ok := t.Claims.(*Token); ok && t.Valid {
return claims, nil
} else {
return nil, err
}
}
+28
View File
@@ -0,0 +1,28 @@
package utils
import (
"encoding/json"
"fmt"
"github.com/sirupsen/logrus"
"knowledge/global"
)
func LogJsonInfo(msg string, v interface{}) {
jsonData, err := json.Marshal(v)
if err != nil {
fmt.Println("Error marshaling struct to JSON:", err)
return
}
jsonString := string(jsonData)
global.Logger.WithFields(logrus.Fields{
"data": jsonString,
}).Info(msg)
}
func LogJsonErr(msg string, v interface{}) {
global.Logger.WithFields(logrus.Fields{
"data": v,
}).Errorf(msg)
}
+89
View File
@@ -0,0 +1,89 @@
package utils
import (
"regexp"
"unicode/utf8"
)
// MaskNameStr 用户名掩码
func MaskNameStr(str string, maskType int) string {
if str == "" {
return str
}
// 使用正则表达式判断是否包含中文字符
chinesePattern := "[\u4e00-\u9fa5]+"
isChinese, _ := regexp.MatchString(chinesePattern, str)
// 使用正则表达式判断是否包含英文字母
englishPattern := "[A-Za-z]+"
isEnglish, _ := regexp.MatchString(englishPattern, str)
// 判断是否包含中文字符
if isChinese {
// 按照中文字符计算长度
strLen := utf8.RuneCountInString(str)
if strLen >= 3 {
if maskType == 1 {
// 三个字符或三个字符以上掐头取尾,中间用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
lastChar, _ := utf8.DecodeLastRuneInString(str)
str = string(firstChar) + "*" + string(lastChar)
} else {
// 首字母保留,后两位用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "**"
}
} else if strLen == 2 {
// 两个字符
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "*"
}
} else if isEnglish {
// 按照英文字串计算长度
strLen := utf8.RuneCountInString(str)
if strLen >= 3 {
if maskType == 1 {
// 三个字符或三个字符以上掐头取尾,中间用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
lastChar, _ := utf8.DecodeLastRuneInString(str)
str = string(firstChar) + "*" + string(lastChar)
} else {
// 首字母保留,后两位用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "**"
}
} else if strLen == 2 {
// 两个字符
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "*"
}
}
return str
}
// MaskPhoneStr 手机号、固话加密
// 固话:0510-89754815 0510-8****815
// 手机号:18221234158 18*******58
func MaskPhoneStr(phone string) string {
if phone == "" {
return phone
}
// 使用正则表达式匹配固定电话
phonePattern := `(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)`
isFixedLine := regexp.MustCompile(phonePattern).MatchString(phone)
if isFixedLine {
// 匹配到固定电话
// 替换匹配的部分为固定格式
return regexp.MustCompile(`(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)`).ReplaceAllString(phone, "$1****$2")
} else {
// 匹配到手机号
// 替换匹配的部分为固定格式
return regexp.MustCompile(`(1[0-9]{1})[0-9]{7}([0-9]{2})`).ReplaceAllString(phone, "$1*******$2")
}
}
+12
View File
@@ -0,0 +1,12 @@
package utils
import "regexp"
// RegexpMobile 手机号匹配
func RegexpMobile(mobile string) bool {
ok, err := regexp.MatchString(`^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$`, mobile)
if err != nil {
return false
}
return ok
}
+22
View File
@@ -0,0 +1,22 @@
package utils
import (
"knowledge/config"
"strings"
)
// RemoveOssDomain 去除oss地址中的前缀
func RemoveOssDomain(url string) string {
if url != "" {
url = strings.Replace(url, config.C.Oss.OssCustomDomainName, "", 1)
}
return url
}
// AddOssDomain 增加oss地址中的前缀
func AddOssDomain(url string) string {
if url == "" {
return ""
}
return config.C.Oss.OssCustomDomainName + url
}
+15
View File
@@ -0,0 +1,15 @@
package utils
import (
"github.com/go-playground/validator/v10"
"knowledge/global"
)
// Translate 检验并返回检验错误信息
func Translate(err error) (errMsg string) {
errs := err.(validator.ValidationErrors)
for _, err := range errs {
errMsg = err.Translate(global.Trans)
}
return
}