gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/registry/encoding.go (about) 1 package registry 2 3 import ( 4 "bytes" 5 "compress/zlib" 6 "encoding/hex" 7 "encoding/json" 8 "io/ioutil" 9 "strings" 10 ) 11 12 func encode(txt *mdnsTxt) ([]string, error) { 13 b, err := json.Marshal(txt) 14 if err != nil { 15 return nil, err 16 } 17 18 var buf bytes.Buffer 19 defer buf.Reset() 20 21 w := zlib.NewWriter(&buf) 22 if _, err := w.Write(b); err != nil { 23 return nil, err 24 } 25 w.Close() 26 27 encoded := hex.EncodeToString(buf.Bytes()) 28 29 // individual txt limit 30 if len(encoded) <= 255 { 31 return []string{encoded}, nil 32 } 33 34 // split encoded string 35 var record []string 36 37 for len(encoded) > 255 { 38 record = append(record, encoded[:255]) 39 encoded = encoded[255:] 40 } 41 42 record = append(record, encoded) 43 44 return record, nil 45 } 46 47 func decode(record []string) (*mdnsTxt, error) { 48 encoded := strings.Join(record, "") 49 50 hr, err := hex.DecodeString(encoded) 51 if err != nil { 52 return nil, err 53 } 54 55 br := bytes.NewReader(hr) 56 zr, err := zlib.NewReader(br) 57 if err != nil { 58 return nil, err 59 } 60 61 rbuf, err := ioutil.ReadAll(zr) 62 if err != nil { 63 return nil, err 64 } 65 66 var txt *mdnsTxt 67 68 if err := json.Unmarshal(rbuf, &txt); err != nil { 69 return nil, err 70 } 71 72 return txt, nil 73 }