micro/registry/encoding.go

74 lines
1.1 KiB
Go
Raw Normal View History

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