userAgentPicker.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2017, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package common
  20. import (
  21. "net/http"
  22. "sync/atomic"
  23. )
  24. var registeredUserAgentPicker atomic.Value
  25. func RegisterUserAgentPicker(generator func() string) {
  26. registeredUserAgentPicker.Store(generator)
  27. }
  28. func PickUserAgent() string {
  29. generator := registeredUserAgentPicker.Load()
  30. if generator != nil {
  31. return generator.(func() string)()
  32. }
  33. return ""
  34. }
  35. func UserAgentIfUnset(h http.Header) (http.Header, bool) {
  36. internalUserAgent := false
  37. if _, ok := h["User-Agent"]; !ok {
  38. if h == nil {
  39. h = make(map[string][]string)
  40. }
  41. if FlipCoin() {
  42. h.Set("User-Agent", PickUserAgent())
  43. } else {
  44. h.Set("User-Agent", "")
  45. }
  46. internalUserAgent = true
  47. }
  48. return h, internalUserAgent
  49. }