utils.go 1.09 KB
package utils

import (
	"crypto/md5"
	"encoding/hex"
	"reflect"
	"strings"
	"time"
)

func GetSchemaType(schema interface{}) reflect.Type  {
	s := reflect.TypeOf(schema)
	if s.Kind() == reflect.Ptr {
		s = reflect.TypeOf(schema).Elem()
	}
	return s
}

func GetCollName(schema interface{}) string {
	return strings.ToLower(GetSchemaType(schema).Name())
}

func GetPriKey(schema interface{}) string {
	s := GetSchemaType(schema)

	var pri string
	for i := 0; i < s.NumField(); i++ {
		if s.Field(i).Tag.Get("pri") == "1" {
			pri = strings.ToLower(s.Field(i).Name)
			break
		}
	}
	return pri
}

func FindIndex(schema interface{}) (string, []string){
	s := GetSchemaType(schema)

	var index []string
	for i := 0; i < s.NumField(); i++ {
		if s.Field(i).Tag.Get("index") != "" {
			js := strings.Split(s.Field(i).Tag.Get("json"), ",")
			if len(js) == 0 {
				continue
			}
			index = append(index, js[0])
		}
	}
	return strings.ToLower(s.Name()), index
}

func Md5V(str string) string  {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

func Timex() int64 {
	return time.Now().Unix()
}