Debian Codegraph @

autopaho/examples/docker/subscriber/message-handler.go

raw symbols SCIP
1 /*
2 * Copyright (c) 2024 Contributors to the Eclipse Foundation
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v2.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * https://www.eclipse.org/legal/epl-2.0/
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
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 // handler is a simple struct that provides a function to be called when a message is received. The message is parsed
27 // and the count followed by the raw message is written to the file (this makes it easier to sort the file)
28 type handler struct {
29 writeToStdOut bool
30
31 f *os.File
32 }
33
34 // NewHandler creates a new output handler and opens the output file (if applicable)
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 // Close closes the file
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 // Message is used for marshalling/unmarshalling the JSON message (just a count)
61 type Message struct {
62 Count uint64
63 }
64
65 // handle is called when a message is received
66 func (o *handler) handle(msg *paho.Publish) {
67 // We extract the count and write that out first to simplify checking for missing values
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 // Write out the number (make it long enough that sorting works) and the payload
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 }