1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-11-30 08:06:40 +02:00
go-micro/registry/encoding.go

74 lines
1.1 KiB
Go
Raw Normal View History

2016-03-16 23:23:41 +02:00
package registry
import (
"bytes"
"compress/zlib"
"encoding/hex"
"encoding/json"
"io/ioutil"
2019-01-15 18:50:37 +02:00
"strings"
2016-03-16 23:23:41 +02:00
)
2019-01-15 18:50:37 +02:00
func encode(txt *mdnsTxt) ([]string, error) {
b, err := json.Marshal(txt)
2016-03-16 23:23:41 +02:00
if err != nil {
2019-01-15 18:50:37 +02:00
return nil, err
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
var buf bytes.Buffer
defer buf.Reset()
2016-03-16 23:23:41 +02:00
2019-01-15 18:50:37 +02:00
w := zlib.NewWriter(&buf)
if _, err := w.Write(b); err != nil {
return nil, err
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
w.Close()
2016-03-16 23:23:41 +02:00
2019-01-15 18:50:37 +02:00
encoded := hex.EncodeToString(buf.Bytes())
2016-03-16 23:23:41 +02:00
2019-01-15 18:50:37 +02:00
// individual txt limit
if len(encoded) <= 255 {
return []string{encoded}, nil
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
// split encoded string
var record []string
2016-03-29 19:32:16 +02:00
2019-01-15 18:50:37 +02:00
for len(encoded) > 255 {
record = append(record, encoded[:255])
encoded = encoded[255:]
}
2016-03-16 23:23:41 +02:00
2019-01-15 18:50:37 +02:00
record = append(record, encoded)
2019-01-15 18:50:37 +02:00
return record, nil
}
2016-03-16 23:23:41 +02:00
2019-01-15 18:50:37 +02:00
func decode(record []string) (*mdnsTxt, error) {
encoded := strings.Join(record, "")
2019-01-15 18:50:37 +02:00
hr, err := hex.DecodeString(encoded)
if err != nil {
return nil, err
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
br := bytes.NewReader(hr)
zr, err := zlib.NewReader(br)
if err != nil {
return nil, err
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
rbuf, err := ioutil.ReadAll(zr)
if err != nil {
return nil, err
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
var txt *mdnsTxt
2016-03-16 23:23:41 +02:00
2019-01-15 18:50:37 +02:00
if err := json.Unmarshal(rbuf, &txt); err != nil {
return nil, err
2016-03-16 23:23:41 +02:00
}
2019-01-15 18:50:37 +02:00
return txt, nil
2016-03-16 23:23:41 +02:00
}