github.com/songzhibin97/gkit@v1.2.13/coding/coding.go (about)

     1  package coding
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  	"sync"
     7  )
     8  
     9  // package encoding 各种格式编码解码
    10  
    11  var ErrorTypeCode = errors.New("coding: code type error")
    12  
    13  var registerCode = CodeStorage{storage: map[string]Code{}}
    14  
    15  type (
    16  	// Code coding 接口
    17  	Code interface {
    18  		// Marshal 将v序列化为[]byte
    19  		Marshal(v interface{}) ([]byte, error)
    20  
    21  		// Unmarshal 将[]byte 反序列化为v
    22  		Unmarshal(data []byte, v interface{}) error
    23  
    24  		// Name 返回实际调用编码器的类型, 例如 json、xml、yaml、proto
    25  		Name() string
    26  	}
    27  
    28  	// CodeStorage 注册中心
    29  	CodeStorage struct {
    30  		storage map[string]Code
    31  		sync.Mutex
    32  	}
    33  )
    34  
    35  func RegisterCode(code Code) error {
    36  	if code == nil || len(code.Name()) == 0 {
    37  		return ErrorTypeCode
    38  	}
    39  	registerCode.Lock()
    40  	defer registerCode.Unlock()
    41  	registerCode.storage[strings.ToLower(code.Name())] = code
    42  	return nil
    43  }
    44  
    45  func GetCode(codeName string) Code {
    46  	registerCode.Lock()
    47  	defer registerCode.Unlock()
    48  	return registerCode.storage[strings.ToLower(codeName)]
    49  }