github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcodec/codec.go (about)

     1  package xcodec
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  // Codec is definition of encoding can marshal/unmarshal data
     8  type Codec interface {
     9  	// Name is name/id of this codec strategy, like json/yaml etc...
    10  	Name() string
    11  	Marshal(v interface{}) ([]byte, error)
    12  	Unmarshal(data []byte, v interface{}) error
    13  }
    14  
    15  var codecMap = make(map[string]Codec)
    16  
    17  // Register register codec to global registry.
    18  // If codec with same name exist, the new one will replace the old one
    19  func Register(codec Codec) {
    20  	if _, ok := codecMap[codec.Name()]; ok {
    21  		panic(fmt.Sprintf("codec [%s] already registered", codec.Name()))
    22  	}
    23  	codecMap[codec.Name()] = codec
    24  }
    25  
    26  // Get get codec by name
    27  func Get(name string) (Codec, bool) {
    28  	codec, ok := codecMap[name]
    29  	return codec, ok
    30  }
    31  
    32  // MustGet must get codec by name, if not exists, panic
    33  func MustGet(name string) Codec {
    34  	codec, ok := Get(name)
    35  	if !ok {
    36  		panic(fmt.Errorf("codec %s not exists", name))
    37  	}
    38  	return codec
    39  }