gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/config/type.go (about) 1 package config 2 3 import ( 4 "encoding/json" 5 "gitee.com/sy_183/go-common/id" 6 "gopkg.in/yaml.v3" 7 "strings" 8 ) 9 10 type Type struct { 11 Id uint64 12 Name string 13 Suffixes []string 14 Unmarshaler func([]byte, interface{}) error 15 } 16 17 var typeIdCxt uint64 18 19 func NewType(Name string, Suffixes []string, Unmarshaler func([]byte, interface{}) error) Type { 20 return Type{ 21 Id: id.Uint64Id(&typeIdCxt), 22 Name: Name, 23 Suffixes: Suffixes, 24 Unmarshaler: Unmarshaler, 25 } 26 } 27 28 var ( 29 TypeUnknown = Type{Id: id.Uint64Id(&typeIdCxt), Name: "unknown"} 30 TypeYaml = Type{Id: id.Uint64Id(&typeIdCxt), Name: "yaml", Suffixes: []string{"yaml", "yml"}, Unmarshaler: yaml.Unmarshal} 31 TypeJson = Type{Id: id.Uint64Id(&typeIdCxt), Name: "json", Suffixes: []string{"json"}, Unmarshaler: json.Unmarshal} 32 ) 33 34 var types = []*Type{&TypeYaml, &TypeJson} 35 36 func ProbeType(path string) Type { 37 for _, tpy := range types { 38 for _, suffix := range tpy.Suffixes { 39 if strings.HasSuffix(path, "."+suffix) { 40 return *tpy 41 } 42 } 43 } 44 return TypeUnknown 45 }