~samwhited/xmpp

231b7a5e957fddbc50217030c531350a105f12b4 — Sam Whited 2 months ago 755df84 context_deadline
xmpp, examples: add context to Encode/EncodeElement

Fixes #36

Signed-off-by: Sam Whited <sam@samwhited.com>
4 files changed, 26 insertions(+), 6 deletions(-)

M CHANGELOG.md
M examples/im/main.go
M examples/msgrepl/main.go
M session.go
M CHANGELOG.md => CHANGELOG.md +2 -0
@@ 9,6 9,8 @@ All notable changes to this project will be documented in this file.

- roster: remove workaround for a bug in Go versions prior to 1.14 which is now
  the earliest supported version
- xmpp: the `Encode` and `EncodeElement` methods now take a context and respect
  its deadline

### Added


M examples/im/main.go => examples/im/main.go +3 -3
@@ 139,7 139,7 @@ func main() {
	defer func() {
		if room {
			debug.Printf("leaving the chat room %s…", addr)
			err = session.Encode(stanza.Presence{
			err = session.Encode(ctx, stanza.Presence{
				ID:   "456def",
				From: originJID,
				To:   parsedToAddr,


@@ 182,7 182,7 @@ func main() {
				To:   parsedToAddr,
			},
		}
		err = session.Encode(joinPresence)
		err = session.Encode(ctx, joinPresence)
		if err != nil {
			log.Fatalf("error joining MUC %s: %v", addr, err)
		}


@@ 195,7 195,7 @@ func main() {
			logger.Fatalf("error sending raw XML: %v", err)
		}
	} else {
		err = session.Encode(messageBody{
		err = session.Encode(ctx, messageBody{
			Message: stanza.Message{
				To:   parsedToAddr,
				From: parsedAddr,

M examples/msgrepl/main.go => examples/msgrepl/main.go +1 -1
@@ 153,7 153,7 @@ func main() {

		msg = strings.TrimSpace(msg[idx+1:])

		err = session.Encode(messageBody{
		err = session.Encode(ctx, messageBody{
			Message: stanza.Message{
				To:   parsedToAddr,
				From: parsedAddr,

M session.go => session.go +20 -2
@@ 676,10 676,19 @@ func (s *Session) EncodeIQElement(ctx context.Context, payload interface{}, iq s
// Encode writes the XML encoding of v to the stream.
//
// For more information see "encoding/xml".Encode.
func (s *Session) Encode(v interface{}) error {
func (s *Session) Encode(ctx context.Context, v interface{}) error {
	s.out.Lock()
	defer s.out.Unlock()

	if deadline, ok := ctx.Deadline(); ok {
		err := s.conn.SetDeadline(deadline)
		if err != nil {
			return err
		}
		/* #nosec */
		defer s.conn.SetDeadline(time.Time{})
	}

	return marshal.EncodeXML(s.out.e, v)
}



@@ 687,10 696,19 @@ func (s *Session) Encode(v interface{}) error {
// outermost tag in the encoding.
//
// For more information see "encoding/xml".EncodeElement.
func (s *Session) EncodeElement(v interface{}, start xml.StartElement) error {
func (s *Session) EncodeElement(ctx context.Context, v interface{}, start xml.StartElement) error {
	s.out.Lock()
	defer s.out.Unlock()

	if deadline, ok := ctx.Deadline(); ok {
		err := s.conn.SetDeadline(deadline)
		if err != nil {
			return err
		}
		/* #nosec */
		defer s.conn.SetDeadline(time.Time{})
	}

	return marshal.EncodeXMLElement(s.out.e, v, start)
}