summaryrefslogtreecommitdiff
path: root/xmpp/decoder.go
blob: 070f7918ade0776ed23841c2e068ffea85d13674 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package xmpp

import (
	"crypto/tls"
	"encoding/xml"
	"log"
	"os"
	"io"
	"errors"
)

type decoder struct {
	terminator chan bool
	data chan xml.Token
	decoder *xml.Decoder
	debug *xml.Encoder
}

func newDecoder(conn *tls.Conn) decoder {
	d := decoder{
		make(chan bool),
		make(chan xml.Token),
		xml.NewDecoder(conn),
		xml.NewEncoder(os.Stdout),
	}

	d.debug.Indent("S: ", "    ")

	return d
}

func (r *decoder) run() {
	for {
		select {
		case <-r.terminator:
			return
		default:
			t, err := r.decoder.Token()
			if t != nil && err == nil {
				err := r.debug.EncodeToken(t)
				if err != nil {
					log.Println("Could not encode received XML token to debug output!")
				}
				err = r.debug.Flush()
				if err != nil {
					log.Println("Could not flush debug output after receive!")
				}
				r.data <- t
			}
			if err != nil {
				if errors.Is(err, io.EOF) {
					return
				} else {
					log.Printf("Decoding error: %v", err)
				}
			}
		}
	}
}

func (r *decoder) stop() {
	r.terminator <- true
}