gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/datax/schemax/schema.go (about)

     1  package schemax
     2  
     3  import (
     4  	"encoding/json"
     5  	"gitee.com/zhongguo168a/gocodes/myx/logx"
     6  	"reflect"
     7  	"sync"
     8  )
     9  
    10  type IDecl interface {
    11  	GetIdent() string
    12  	GetName() string
    13  	GetPackage() string
    14  	RefType() string
    15  }
    16  
    17  func ParseJson(content string) (err error) {
    18  	m := map[string]interface{}{}
    19  	err = json.Unmarshal([]byte(content), &m)
    20  	return
    21  }
    22  
    23  var (
    24  	data = &sync.Map{}
    25  )
    26  
    27  func GetDeclByKey(key string) IDecl {
    28  	val, has := data.Load(key)
    29  	if !has {
    30  		return nil
    31  	}
    32  	return val.(IDecl)
    33  }
    34  
    35  func AddDecls(decls []IDecl, prefix string) (err error) {
    36  	for _, val := range decls {
    37  		err = AddDecl(val, prefix)
    38  		if err != nil {
    39  			return
    40  		}
    41  	}
    42  
    43  	return
    44  }
    45  
    46  func AddDecl(decl IDecl, prefix string) (err error) {
    47  	ident := prefix + decl.GetName()
    48  	_, has := data.Load(ident)
    49  	if has {
    50  		logx.Warn("存在相同编号的schema声明: " + ident)
    51  	}
    52  	data.Store(ident, decl)
    53  	return
    54  }
    55  
    56  func GetDeclByStruct(st interface{}) IDecl {
    57  	decl := GetDeclByKey(GetDeclByStructKey(st))
    58  	if decl == nil {
    59  		decl = CreateDecl(reflect.TypeOf(st))
    60  	}
    61  	return decl
    62  }
    63  
    64  func GetDeclByStructKey(st interface{}) string {
    65  	obj, ok := st.(IObject)
    66  	if ok {
    67  		return obj.RefType()
    68  	}
    69  	rtyp := reflect.TypeOf(st)
    70  	if rtyp.Kind() == reflect.Ptr {
    71  		rtyp = rtyp.Elem()
    72  	}
    73  	return rtyp.String()
    74  }