记得关注我,谢谢
package util
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"reflect"
"regexp"
"server/db/filedb"
"strconv"
"strings"
"sync/atomic"
"time"
)
//转换工具类
func CurTimeOfMills() int64 {
return time.Now().UnixNano() / 1000000
}
const path = "/bin/data/idCache"
func init() {
root, _ := os.Getwd()
data := filedb.NewFileData(root+path, nil).Get()
seedNum = StringToInt64(string(data))
}
func SavingCache() {
root, _ := os.Getwd()
if filedb.NewFileData(root+path, seedNum).SaveNoLock() {
fmt.Println("IdCache is saving succeed!!")
} else {
log.Println("IdCache is saving failed!!")
}
}
const base_format = "2006-01-02 15:04:05"
//系统当前时间的秒数
func CurTimeOfSecond() int64 {
return time.Now().Unix()
}
//转换当前时间为字符串输出
func CurTimeOfFormat(format string) string {
if format == "" {
return time.Now().Format(base_format)
} else {
return time.Now().Format(format)
}
}
func TimeStampToString(mills int64) string {
//时间戳转日期格式
date_time := time.Unix(mills, 0).Format(base_format)
return date_time
}
//时间字符串转换为时间戳
func TimeFormatToStamp(format, timeFormat string) int64 {
if format == "" {
parse_str_time, _ := time.Parse(base_format, timeFormat)
return parse_str_time.Unix()
} else {
parse_str_time, _ := time.Parse(format, timeFormat)
return parse_str_time.Unix()
}
}
//截断切片
func DeleteSlice(slicePtr interface{}, index int) (interface{}, error) {
sliceValue := reflect.ValueOf(slicePtr)
length := sliceValue.Len()
if slicePtr == nil || length == 0 || (length-1) < index {
return nil, errors.New("error")
}
if length-1 == index {
return sliceValue.Slice(0, index).Interface(), nil
} else if (length - 1) >= index {
return reflect.AppendSlice(sliceValue.Slice(0, index), sliceValue.Slice(index+1, length)).Interface(), nil
}
return nil, errors.New("error")
}
//获取通过POST_GET方式访问URL获取服务器数据
func HttpReqToUrl(urlStr string, data map[string][]string) []byte {
client := &http.Client{}
if data == nil {
request, _ := http.NewRequest("POST", urlStr, nil)
request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
request.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
request.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
request.Header.Set("Cache-Control", "max-age=0")
request.Header.Set("Connection", "keep-alive")
request.Header.Set("User-Agent", "chrome 100")
response, _ := client.Do(request)
if response.StatusCode == 200 {
body, _ := ioutil.ReadAll(response.Body)
return body
}
} else {
response, _ := http.PostForm("http://127.0.0.1", data)
if response.StatusCode == 200 {
body, _ := ioutil.ReadAll(response.Body)
return body
}
}
return nil
}
//将指定的类型转化为字符串
func AllToString(value interface{}) string {
valT_ := reflect.TypeOf(value).Kind().String()
switch {
case strings.EqualFold(valT_, "struct"):
bytes, _ := json.Marshal(value)
return string(bytes)
case strings.EqualFold(valT_, "ptr"):
bytes, _ := json.Marshal(value)
return string(bytes)
case strings.EqualFold(valT_, "bool"):
if value == true {
return "true"
} else {
return "false"
}
case strings.EqualFold(valT_, "string"):
return value.(string)
case strings.Contains(valT_, "uint"):
return strconv.FormatUint(reflect.ValueOf(value).Uint(), 10)
case strings.Contains(valT_, "int"):
return strconv.FormatInt(reflect.ValueOf(value).Int(), 10)
case strings.Contains(valT_, "float"):
return strconv.FormatFloat(reflect.ValueOf(value).Float(), 'E', -1, 64)
default:
return ""
}
}
//string转int
func StringToInt(val string) int {
if val == "" {
return 0
}
valI, err := strconv.Atoi(val)
if err != nil {
fmt.Println(err, val)
}
return valI
}
//复制对象 对象内的结构体无法改变地址 会被二次更改
func Clone(oldPtr, newPtr interface{}) {
data, err := json.Marshal(oldPtr)
CheckError(err)
CheckError(json.Unmarshal(data, newPtr))
}
//string转int64
func StringToInt64(val string) int64 {
if val == "" {
return 0
}
int64, err := strconv.ParseInt(val, 10, 64)
if err != nil {
fmt.Println(err, val)
}
return int64
}
//string转float64
func StringToFloat64(val string) float64 {
if val == "" {
return 0
}
float64, err := strconv.ParseFloat(val, 64)
if err != nil {
fmt.Println(err, val)
}
return float64
}
//string转float64
func StringToFloat32(val string) float32 {
if val == "" {
return 0
}
float64, err := strconv.ParseFloat(val, 64)
if err != nil {
fmt.Println(err, val)
}
return float32(float64)
}
func StringToInt32(val string) int32 {
if val == "" {
return 0
}
int64, err := strconv.ParseInt(val, 10, 64)
if err != nil {
fmt.Println(err, val)
}
return int32(int64)
}
//通过结构体的方法名和参数调用结构体的方法
//impl结构体 methodName方法名 params传入参数
func CallStruceFuncByName(implPtr interface{}, methodName string, params ...interface{}) []interface{} {
reflectValue := make([]reflect.Value, 0)
for _, value := range params {
reflectValue = append(reflectValue, reflect.ValueOf(value))
}
returnArr := make([]interface{}, 0)
returnValue := reflect.ValueOf(implPtr).Elem().MethodByName(methodName).Call(reflectValue)
for _, val := range returnValue {
returnArr = append(returnArr, val.Interface())
}
return returnArr
}
//获取结构体的所有属性reflect.value集合
func GetStructReflectArr(implPtr interface{}) []interface{} {
val := reflect.ValueOf(implPtr)
tempArr := make([]interface{}, 0)
if val.Kind() != reflect.Ptr && val.Elem().Kind() == reflect.Struct {
fmt.Println("expect struct")
return tempArr
}
//获取字段的类型
for i := 0; i < val.Elem().NumField(); i++ {
keyOfField := val.Elem().Field(i).Interface() // val.Elem().Field(i)
tempArr = append(tempArr, keyOfField)
}
return tempArr
}
//通过对象的属性名获取对象的属性值
//impl 结构体 fieldName 字段名
func GetValueByFieldName(implPtr interface{}, fieldName string) interface{} {
type_ := reflect.ValueOf(implPtr).Elem() //获得对象的反射对象
return type_.FieldByName(fieldName).Interface() //通过反射对象获取元对象的字段属性值
}
//获取结构体的名称
func GetStructName(implPtr interface{}) string {
fullName := reflect.ValueOf(implPtr).Elem().Type().String()
return fullName[strings.LastIndex(fullName, ".")+1:]
}
//通过结构体的属性字段名设置属性值
func SetValueByFieldName(implPtr interface{}, fieldName string, valuePtr interface{}) bool {
type_ := reflect.ValueOf(implPtr).Elem() //获得对象的反射对象
this := type_.FieldByName(fieldName)
if this.CanSet() {
this.Set(reflect.ValueOf(valuePtr).Elem())
return true
}
return false
}
//获取结构体的所有属性名和属性值的map集合
func GetStructFieldMap(implPtr interface{}) map[string]reflect.Value {
tempMap := make(map[string]reflect.Value)
val := reflect.ValueOf(implPtr)
//获取字段的类型
for i := 0; i < val.Elem().NumField(); i++ {
valueOfField := val.Elem().Field(i)
keyOfField := val.Type().Elem().Field(i).Name
tempMap[keyOfField] = valueOfField
}
return tempMap
}
func Int64ToBytes(n int64) []byte {
var buffer bytes.Buffer
err := binary.Write(&buffer, binary.BigEndian, n)
if err != nil {
return nil
}
return buffer.Bytes()
}
func BytesToInt64(bys []byte) int64 {
return int64(binary.BigEndian.Uint64(bys))
}
//整形转换成字节
func IntToBytes(n int) []byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
//字节转换成整形
func BytesToInt(b []byte) int {
bytesBuffer := bytes.NewBuffer(b)
var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
return int(x)
}
func Float32ToByte(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)
return bytes
}
func ByteToFloat32(bytes []byte) float32 {
bits := binary.LittleEndian.Uint32(bytes)
return math.Float32frombits(bits)
}
func Float64ToByte(float float64) []byte {
bits := math.Float64bits(float)
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, bits)
return bytes
}
func ByteToFloat64(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
return math.Float64frombits(bits)
}
//连接所有的字符串
func CombineString(str ...string) string {
total := make([]byte, 0, 1024)
for _, s := range str {
total = append(total, []byte(s)...)
}
return string(total)
}
//将字符串大写字母换成 _+大写 如 AbcDef -> abc_def
func CaseFormatString(str string) string {
f := make([]byte, 0)
for i, s := range str {
s_ := string(s)
r, _ := regexp.MatchString("[A-Z]", s_)
if r {
if i == 0 {
by := []byte( strings.ToLower(s_))
f = append(f, by...)
} else {
by := []byte("_" + strings.ToLower(s_))
f = append(f, by...)
}
} else {
f = append(f, byte(s))
}
}
return string(f)
}
//获取一个指定路径下的所有子路径内的文件名和其对应的绝对路径
func GetAllFiles(path, originPath string, endMask ...string) map[string]string {
temp := make(map[string]string, 0)
rd, _ := ioutil.ReadDir(path)
for _, fi := range rd {
if fi.IsDir() {
dirMap := GetAllFiles(path+fi.Name()+"/", originPath, endMask...)
for k, v := range dirMap { //将其他目录下的信息汇总
temp[k] = v
}
} else {
//fileNameNoEnd := fi.Name()[0:strings.LastIndex(fi.Name(), ".")]
endStr := fi.Name()[strings.LastIndex(fi.Name(), ".")+1:]
if caseOnce(endStr, endMask) {
key := strings.Replace(path+fi.Name(), originPath, "", 1)
temp[key] = path + fi.Name()
}
}
}
return temp
}
//或逻辑
func caseOnce(a string, arr []string) bool {
for _, str := range arr {
if strings.EqualFold(a, str) {
return true
}
}
return false
}
//通用方法 检测错误并输出
func CheckError(err error) bool {
if err != nil {
log.Println(err)
return false
}
return true
}
//创建唯一的int64 可以解决并发问题
func CreateUniqueInt64() int64 {
seed := CurTimeOfSecond() //去除毫秒大数
inc := atomic.AddInt64(&seedNum, 123)
return seed + inc
}
var seedNum int64 = 0 //全局增长种子
//创建唯一的int32 可以解决并发问题
func CreateUniqueInt32() int32 {
seed := int32(CurTimeOfSecond())
inc := int32(atomic.AddInt64(&seedNum, 123))
return seed + inc
}