main.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package main
  2. import (
  3. "context"
  4. firebase "firebase.google.com/go/v4"
  5. "firebase.google.com/go/v4/messaging"
  6. "flag"
  7. "fmt"
  8. "google.golang.org/api/option"
  9. "os"
  10. "strings"
  11. )
  12. func main() {
  13. conffile := flag.String("config", "/etc/fbsend/fbsend.json", "config file")
  14. flag.Parse()
  15. if flag.NArg() < 2 {
  16. fail("Syntax: fbsend [-config FILE] topic key=value ...")
  17. }
  18. topic := flag.Arg(0)
  19. data := make(map[string]string)
  20. for i := 1; i < flag.NArg(); i++ {
  21. kv := strings.SplitN(flag.Arg(i), "=", 2)
  22. if len(kv) != 2 {
  23. fail(fmt.Sprintf("Invalid argument: %s (%v)", flag.Arg(i), kv))
  24. }
  25. data[kv[0]] = kv[1]
  26. }
  27. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(*conffile))
  28. if err != nil {
  29. fail(err.Error())
  30. }
  31. msg, err := fb.Messaging(context.Background())
  32. if err != nil {
  33. fail(err.Error())
  34. }
  35. _, err = msg.Send(context.Background(), &messaging.Message{
  36. Topic: topic,
  37. Data: data,
  38. })
  39. if err != nil {
  40. fail(err.Error())
  41. }
  42. fmt.Println("Sent successfully")
  43. }
  44. func fail(s string) {
  45. fmt.Println(s)
  46. os.Exit(1)
  47. }