2016-03-09 02:49:27 +00:00
|
|
|
package respond
|
|
|
|
|
|
|
|
import (
|
2019-01-24 01:54:21 +00:00
|
|
|
"bytes"
|
|
|
|
"compress/flate"
|
|
|
|
"encoding/json"
|
2016-03-09 02:49:27 +00:00
|
|
|
"net"
|
2019-01-24 01:54:21 +00:00
|
|
|
|
|
|
|
"github.com/FreifunkBremen/yanic/data"
|
2016-03-09 02:49:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2017-12-05 22:17:49 +00:00
|
|
|
// default multicast group used by announced
|
|
|
|
multicastAddressDefault = "ff02:0:0:0:0:0:2:1001"
|
|
|
|
|
2016-03-09 02:49:27 +00:00
|
|
|
// default udp port used by announced
|
2017-01-29 21:14:40 +00:00
|
|
|
port = 1001
|
2016-03-09 02:49:27 +00:00
|
|
|
|
|
|
|
// maximum receivable size
|
2019-01-24 01:54:21 +00:00
|
|
|
MaxDataGramSize = 8192
|
2016-03-09 02:49:27 +00:00
|
|
|
)
|
|
|
|
|
2017-10-18 16:22:14 +00:00
|
|
|
// Response of the respond request
|
2016-03-09 02:49:27 +00:00
|
|
|
type Response struct {
|
2017-10-18 16:22:14 +00:00
|
|
|
Address *net.UDPAddr
|
2016-03-09 02:49:27 +00:00
|
|
|
Raw []byte
|
|
|
|
}
|
2019-01-24 01:54:21 +00:00
|
|
|
|
|
|
|
func NewRespone(res *data.ResponseData, addr *net.UDPAddr) (*Response, error) {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
flater, err := flate.NewWriter(buf, flate.BestCompression)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer flater.Close()
|
|
|
|
|
|
|
|
if err = json.NewEncoder(flater).Encode(res); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = flater.Flush()
|
|
|
|
|
|
|
|
return &Response{
|
|
|
|
Raw: buf.Bytes(),
|
|
|
|
Address: addr,
|
|
|
|
}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (res *Response) parse() (*data.ResponseData, error) {
|
|
|
|
// Deflate
|
|
|
|
deflater := flate.NewReader(bytes.NewReader(res.Raw))
|
|
|
|
defer deflater.Close()
|
|
|
|
|
|
|
|
// Unmarshal
|
|
|
|
rdata := &data.ResponseData{}
|
|
|
|
err := json.NewDecoder(deflater).Decode(rdata)
|
|
|
|
|
|
|
|
return rdata, err
|
|
|
|
}
|