stats.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package web
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "path/filepath"
  6. "strconv"
  7. "sync"
  8. "github.com/gorilla/mux"
  9. )
  10. // Stats implement a statistics counter for hits to the FizzBuzz endpoint.
  11. type Stats struct {
  12. sync.Mutex
  13. hits map[string]int
  14. maxKey string
  15. maxHits int
  16. }
  17. // Incr records a hit in a way that supports reporting in O(1) time and space.
  18. func (s *Stats) Incr(int1, int2, limit int, str1, str2 string) {
  19. s.Lock()
  20. defer s.Unlock()
  21. key := filepath.Join(strconv.Itoa(int1), strconv.Itoa(int2), strconv.Itoa(limit), str1, str2)
  22. s.hits[key]++
  23. if s.hits[key] <= s.maxHits {
  24. return
  25. }
  26. s.maxHits = s.hits[key]
  27. s.maxKey = key
  28. }
  29. // MarshalJSON implements [json.Marshaler].
  30. func (s *Stats) MarshalJSON() ([]byte, error) {
  31. raw := map[string]any{
  32. "key": s.maxKey,
  33. "hits": s.maxHits,
  34. }
  35. return json.Marshal(raw)
  36. }
  37. // Handler provides the statistics endpoint.
  38. func (s *Stats) Handler() http.HandlerFunc {
  39. return func(w http.ResponseWriter, r *http.Request) {
  40. w.Header().Set(CT, JSON)
  41. enc := json.NewEncoder(w)
  42. enc.SetEscapeHTML(true)
  43. enc.SetIndent("", " ")
  44. enc.Encode(s)
  45. }
  46. }
  47. // Middleware provides the statistics middleware.
  48. func (s *Stats) Middleware() mux.MiddlewareFunc {
  49. return func(h http.Handler) http.Handler {
  50. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  51. int1, int2, limit, str1, str2, status := argsFromRequest(r)
  52. if status >= http.StatusBadRequest {
  53. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  54. return
  55. }
  56. s.Incr(int1, int2, limit, str1, str2)
  57. h.ServeHTTP(w, r)
  58. })
  59. }
  60. }
  61. func NewStats() *Stats {
  62. return &Stats{hits: make(map[string]int)}
  63. }