micro/registry/encoding.go

74 lines
1.1 KiB
Go
Raw Normal View History

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