util.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package server
  2. import (
  3. "encoding/json"
  4. "firebase.google.com/go/messaging"
  5. "net/http"
  6. "strings"
  7. )
  8. const (
  9. fcmMessageLimit = 4000
  10. )
  11. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  12. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  13. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  14. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  15. s, err := json.Marshal(m)
  16. if err != nil {
  17. return m
  18. }
  19. if len(s) > fcmMessageLimit {
  20. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  21. message, ok := m.Data["message"]
  22. if ok && len(message) > over {
  23. m.Data["truncated"] = "1"
  24. m.Data["message"] = message[:len(message)-over]
  25. }
  26. }
  27. return m
  28. }
  29. func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
  30. value := strings.ToLower(readParam(r, names...))
  31. if value == "" {
  32. return defaultValue
  33. }
  34. return value == "1" || value == "yes" || value == "true"
  35. }
  36. func readParam(r *http.Request, names ...string) string {
  37. for _, name := range names {
  38. value := r.Header.Get(name)
  39. if value != "" {
  40. return strings.TrimSpace(value)
  41. }
  42. }
  43. for _, name := range names {
  44. value := r.URL.Query().Get(strings.ToLower(name))
  45. if value != "" {
  46. return strings.TrimSpace(value)
  47. }
  48. }
  49. return ""
  50. }