main.go 1.1 KB

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