stat.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "github.com/fjl/go-couchdb"
  4. "log"
  5. )
  6. type CStatDoc struct {
  7. Total int
  8. Data map[string]int
  9. }
  10. var statsDb *couchdb.DB
  11. func GetStat(docId string) (ret *CStatDoc, err error) {
  12. ret = &CStatDoc{}
  13. if err = statsDb.Get(docId, ret, nil); err == nil {
  14. if ret.Data == nil {
  15. ret.Data = make(map[string]int)
  16. }
  17. } else if couchdb.NotFound(err) {
  18. if _, err = statsDb.Put(docId, ret, ""); err == nil {
  19. ret, err = GetStat(docId)
  20. }
  21. }
  22. return
  23. }
  24. func SetStat(docId string, old *CStatDoc) {
  25. if rev, err := statsDb.Rev(docId); err == nil {
  26. if _, err = statsDb.Put(docId, old, rev); err != nil {
  27. log.Println(err)
  28. }
  29. }
  30. }
  31. const countId = "count"
  32. const totalId = "total"
  33. func IncStat(user string) {
  34. if s, err := GetStat(totalId); err == nil {
  35. if _, ok := s.Data[user]; ok {
  36. s.Data[user] = s.Data[user] + 1
  37. } else {
  38. s.Data[user] = 1
  39. }
  40. s.Total++
  41. SetStat(totalId, s)
  42. }
  43. }
  44. func IncStatLen(user, msg string) {
  45. count := len([]rune(msg))
  46. if s, err := GetStat(countId); err == nil {
  47. if _, ok := s.Data[user]; ok {
  48. s.Data[user] = s.Data[user] + count
  49. } else {
  50. s.Data[user] = count
  51. }
  52. s.Total += count
  53. SetStat(countId, s)
  54. }
  55. }