communicate/communicator.go

54 lines
1.0 KiB
Go
Raw Normal View History

2016-11-28 05:13:15 +00:00
package communicate
import (
"bytes"
2016-11-30 07:26:53 +00:00
"compress/gzip"
2016-11-28 05:13:15 +00:00
"encoding/json"
"loafle.com/commons/communicate/events"
"net/http"
)
type communicator struct {
2016-11-28 05:43:22 +00:00
Queue chan *events.Event
RootURL string
2016-11-28 05:13:15 +00:00
}
func NewCommunicator() *communicator {
return &communicator{Queue: make(chan *events.Event, 10)}
}
func (c *communicator) addEvent(e *events.Event) {
c.Queue <- e
}
2016-11-30 07:26:53 +00:00
func CompressDataGzip(data []byte) []byte {
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(data)
w.Close()
return b.Bytes()
}
2016-11-30 07:12:28 +00:00
2016-11-28 05:13:15 +00:00
func (c *communicator) start() {
go func() {
for e := range c.Queue {
go func(event *events.Event) {
m := event.Data.(events.URLMaker)
data, _ := json.Marshal(event)
2016-11-30 07:12:28 +00:00
// compress , accept-encoding : gzip
2016-11-30 07:26:53 +00:00
res, err := http.Post(GetRootURL()+m.GetUrl(), "application/json", bytes.NewBuffer(CompressDataGzip(data)))
//res, err := http.Post(GetRootURL()+m.GetUrl(), "application/json", bytes.NewBuffer(data))
2016-11-30 05:44:35 +00:00
// todo timeout,error
if err != nil {
}
if res.StatusCode != 200 && res.StatusCode != 201 {
}
2016-11-28 05:13:15 +00:00
}(e)
}
}()
}