micro-register-mdns/encoding.go

74 lines
1.1 KiB
Go
Raw Normal View History

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