util.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/emersion/go-smtp"
  5. "net/http"
  6. "strings"
  7. )
  8. func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
  9. value := strings.ToLower(readParam(r, names...))
  10. if value == "" {
  11. return defaultValue
  12. }
  13. return value == "1" || value == "yes" || value == "true"
  14. }
  15. func readParam(r *http.Request, names ...string) string {
  16. value := readHeaderParam(r, names...)
  17. if value != "" {
  18. return value
  19. }
  20. return readQueryParam(r, names...)
  21. }
  22. func readHeaderParam(r *http.Request, names ...string) string {
  23. for _, name := range names {
  24. value := r.Header.Get(name)
  25. if value != "" {
  26. return strings.TrimSpace(value)
  27. }
  28. }
  29. return ""
  30. }
  31. func readQueryParam(r *http.Request, names ...string) string {
  32. for _, name := range names {
  33. value := r.URL.Query().Get(strings.ToLower(name))
  34. if value != "" {
  35. return strings.TrimSpace(value)
  36. }
  37. }
  38. return ""
  39. }
  40. func logMessagePrefix(v *visitor, m *message) string {
  41. return fmt.Sprintf("%s/%s/%s", v.ip, m.Topic, m.ID)
  42. }
  43. func logHTTPPrefix(v *visitor, r *http.Request) string {
  44. requestURI := r.RequestURI
  45. if requestURI == "" {
  46. requestURI = r.URL.Path
  47. }
  48. return fmt.Sprintf("%s HTTP %s %s", v.ip, r.Method, requestURI)
  49. }
  50. func logSMTPPrefix(state *smtp.ConnectionState) string {
  51. return fmt.Sprintf("%s/%s SMTP", state.Hostname, state.RemoteAddr.String())
  52. }