l_excel_export/pkg/pkg.go

119 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package pkg
import (
"encoding/json"
"fmt"
"os"
"reflect"
"strings"
"time"
)
type ()
func DefaultLogPath(jobName string) (string, error) {
path, err := os.Getwd()
path = fmt.Sprintf("%s/%s/%s", path, "log/export", jobName)
err = CheckDir(path)
return path, err
}
func CheckDir(path string) error {
// 判断目录是否存在
if _, err := os.Stat(path); os.IsNotExist(err) {
// 如果目录不存在,则创建它
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
} else if err != nil {
// 如果Stat返回了其他错误比如权限问题
return err
}
return nil
}
func CreateTaskId() string {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
// toMap 将结构体转换为map[string]interface{}
// StructToMap 将一个struct转换为map[string]interface{}
func StructToMap(obj interface{}) map[string]interface{} {
// 获取obj的类型
val := reflect.ValueOf(obj)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
// 确保obj是一个struct
if val.Kind() != reflect.Struct {
return nil
}
// 创建一个map来保存结果
data := make(map[string]interface{})
// 遍历struct的字段
for i := 0; i < val.NumField(); i++ {
// 获取字段的类型和值
valueField := val.Field(i)
typeField := val.Type().Field(i)
jsonTag := typeField.Tag.Get("json")
if idx := strings.Index(jsonTag, ","); idx != -1 {
// 如果有逗号,则取逗号之前的部分
jsonTag = jsonTag[:idx]
}
// 忽略未导出的字段(字段名首字母小写)
if !typeField.IsExported() {
continue
}
// 将字段名和值添加到map中
data[jsonTag] = valueField.Interface()
}
return data
}
func GetData(data interface{}) (out []map[string]interface{}) {
switch data.(type) {
case []map[string]interface{}:
for _, item := range data.([]map[string]interface{}) {
out = append(out, item)
}
case []map[string]string:
for _, maps := range data.([]map[string]string) {
newMap := make(map[string]interface{})
for key, item := range maps {
newMap[key] = item
}
out = append(out, newMap)
}
case []interface{}:
for _, item := range data.([]interface{}) {
dataMap := StructToMap(item)
if dataMap == nil {
return nil
}
out = append(out, dataMap)
}
case string:
err := json.Unmarshal([]byte(data.(string)), &out)
if err != nil {
return nil
}
case []byte:
err := json.Unmarshal(data.([]byte), &out)
if err != nil {
return nil
}
default:
return nil
}
return
}