gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/config.v2/type.go (about)

     1  package config
     2  
     3  import (
     4  	"gitee.com/sy_183/go-common/id"
     5  	"gitee.com/sy_183/go-common/lock"
     6  	"strings"
     7  	"sync"
     8  )
     9  
    10  type Type struct {
    11  	Id       uint64
    12  	Name     string
    13  	Suffixes []string
    14  	Parser   Parser
    15  }
    16  
    17  var typeIdCxt uint64
    18  
    19  func NewType(Name string, Suffixes []string, parser Parser) Type {
    20  	return Type{
    21  		Id:       id.Uint64Id(&typeIdCxt),
    22  		Name:     Name,
    23  		Suffixes: Suffixes,
    24  		Parser:   parser,
    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"}, Parser: YamlParser{}}
    31  	TypeJson    = Type{Id: id.Uint64Id(&typeIdCxt), Name: "json", Suffixes: []string{"json"}, Parser: JsonParser{}}
    32  )
    33  
    34  var types = []Type{TypeYaml, TypeJson}
    35  var typesLock sync.RWMutex
    36  
    37  func RegisterType(typ Type) {
    38  	lock.LockDo(&typesLock, func() {
    39  		types = append(types, typ)
    40  	})
    41  }
    42  
    43  func ProbeType(path string) Type {
    44  	return lock.RLockGet(&typesLock, func() Type {
    45  		for _, tpy := range types {
    46  			for _, suffix := range tpy.Suffixes {
    47  				if strings.HasSuffix(path, "."+suffix) {
    48  					return tpy
    49  				}
    50  			}
    51  		}
    52  		return TypeUnknown
    53  	})
    54  }