-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsample.go
111 lines (92 loc) · 2.39 KB
/
sample.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"github.com/PCS-Indonesia/pcspubsub/pubsubclient"
"github.com/joho/godotenv"
)
func init() {
err := godotenv.Load()
if err != nil {
log.Println("can't load env")
}
os.Setenv("ID", "Asia/Jakarta")
}
func main() {
var arg string
if len(os.Args) > 1 {
arg = os.Args[1]
}
switch arg {
case "pub":
pub()
case "script":
createSub()
default:
sub()
}
}
func pub() {
var message pubsubclient.CommandMessage
message.Command = "notify"
message.Payload = "lorem ipsum dolor sit amet"
message.ID = 0
message.Detail = "john doe"
topic := os.Getenv("PUBSUB_MMS_TOPIC")
ctx := context.TODO()
client, err := pubsubclient.NewPubSubClient(ctx, os.Getenv("PUBSUB_PROJECT_ID"), os.Getenv("PUBSUB_CREDENTIAL"), 1)
if err != nil {
log.Fatalf("Failed to create Pub/Sub client: %v", err)
}
err = client.PublishMessage(topic, message)
fmt.Printf("Message: %+v\n", message)
if err != nil {
log.Printf("System: Error publish message topic %s, error: %v", topic, err)
}
}
func createSub() {
ctx := context.TODO()
client, err := pubsubclient.NewPubSubClient(ctx, os.Getenv("PUBSUB_PROJECT_ID"), os.Getenv("PUBSUB_CREDENTIAL"), 1)
if err != nil {
log.Fatalf("Failed to create Pub/Sub client: %v", err)
}
if _, err := client.CreateSubscription(os.Getenv("PUBSUB_MMS_SUBS"), os.Getenv("PUBSUB_MMS_TOPIC")); err != nil {
log.Printf("Failed to create subscription: %v", err)
} else {
log.Println("Subscription created")
}
}
func sub() {
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, os.Interrupt, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
client, err := pubsubclient.NewPubSubClient(ctx, os.Getenv("PUBSUB_PROJECT_ID"), os.Getenv("PUBSUB_CREDENTIAL"), 1)
if err != nil {
log.Fatalf("Failed to create Pub/Sub client: %v", err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
sub := os.Getenv("PUBSUB_MMS_SUBS")
err = client.ReceiveMessages(sub, subFunction)
if err != nil {
log.Panicf("Failed to receive messages from : %s, %v\n", sub, err)
}
log.Println("System has shutdown gracefully")
}()
// Cancel the context when a signal is received
<-sigchan
cancel()
// Wait for the goroutine to finish
wg.Wait()
}
func subFunction(ctx context.Context, msg pubsubclient.CommandMessage) error {
fmt.Printf("Message: %+v\n", msg)
return nil
}