package microservice import ( "context" "log" "net" "git.ali33.ru/fcg-xvii/go-tools/json" ) func MakeProtocolJSON(conn net.Conn, ctx context.Context, receiveBuf int) *ProtocolJSON { proto := &ProtocolJSON{ receiver: make(chan json.Map, receiveBuf), } proto.ctx, proto.cancel = context.WithCancel(ctx) proto.proto = MakeProtocolData(conn, proto.ctx) // receiver go proto.receive() return proto } type ProtocolJSON struct { proto *ProtocolData receiver chan json.Map ctx context.Context cancel context.CancelFunc } func (s *ProtocolJSON) receive() { defer func() { log.Println("JSON receiver closed") s.cancel() close(s.receiver) }() for { select { case <-s.ctx.Done(): //s.proto.Close() return case <-s.proto.Context().Done(): return case data, ok := <-s.proto.Receiver(): if !ok { return } var m json.Map if err := json.Unmarshal(data, &m); err != nil { log.Println("Protocol JSON parse error:", err) log.Println(string(data)) return } select { case s.receiver <- m: default: } } } } func (s *ProtocolJSON) Context() context.Context { return s.ctx } func (s *ProtocolJSON) Receiver() <-chan json.Map { return s.receiver } func (s *ProtocolJSON) Send(m json.Map) { s.proto.Send(m.JSON()) } func (s *ProtocolJSON) Close() { s.proto.Close() }