| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
package main |
| 17 |
|
| 18 |
import ( |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"os" |
| 22 |
|
| 23 |
"github.com/eclipse/paho.golang/paho" |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
type handler struct { |
| 29 |
writeToStdOut bool |
| 30 |
|
| 31 |
f *os.File |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
func NewHandler(writeToDisk bool, fileName string, writeToStdOut bool) *handler { |
| 36 |
var f *os.File |
| 37 |
if writeToDisk { |
| 38 |
var err error |
| 39 |
f, err = os.Create(fileName) |
| 40 |
if err != nil { |
| 41 |
panic(err) |
| 42 |
} |
| 43 |
} |
| 44 |
return &handler{ |
| 45 |
writeToStdOut: writeToStdOut, |
| 46 |
f: f, |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
func (o *handler) Close() { |
| 52 |
if o.f != nil { |
| 53 |
if err := o.f.Close(); err != nil { |
| 54 |
fmt.Printf("ERROR closing file: %s", err) |
| 55 |
} |
| 56 |
o.f = nil |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
type Message struct { |
| 62 |
Count uint64 |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
func (o *handler) handle(msg *paho.Publish) { |
| 67 |
|
| 68 |
var m Message |
| 69 |
if err := json.Unmarshal(msg.Payload, &m); err != nil { |
| 70 |
fmt.Printf("Message could not be parsed (%s): %s", msg.Payload, err) |
| 71 |
} |
| 72 |
if o.f != nil { |
| 73 |
|
| 74 |
if _, err := o.f.WriteString(fmt.Sprintf("%09d %s\n", m.Count, msg.Payload)); err != nil { |
| 75 |
fmt.Printf("ERROR writing to file: %s", err) |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
if o.writeToStdOut { |
| 80 |
fmt.Printf("received message: %s\n", msg.Payload) |
| 81 |
} |
| 82 |
} |