Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stats.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package proxy
  2. import (
  3. "encoding/json"
  4. "net"
  5. "net/http"
  6. "strconv"
  7. "sync/atomic"
  8. "time"
  9. )
  10. type statsUptime time.Time
  11. func (s statsUptime) MarshalJSON() ([]byte, error) {
  12. uptime := int(time.Since(time.Time(s)).Seconds())
  13. return []byte(strconv.Itoa(uptime)), nil
  14. }
  15. type Stats struct {
  16. AllConnections uint64 `json:"all_connections"`
  17. ActiveConnections uint32 `json:"active_connections"`
  18. Traffic struct {
  19. Incoming uint64 `json:"incoming"`
  20. Outgoing uint64 `json:"outgoing"`
  21. } `json:"traffic"`
  22. Uptime statsUptime `json:"uptime"`
  23. }
  24. func (s *Stats) newConnection() {
  25. atomic.AddUint64(&s.AllConnections, 1)
  26. atomic.AddUint32(&s.ActiveConnections, 1)
  27. }
  28. func (s *Stats) closeConnection() {
  29. atomic.AddUint32(&s.ActiveConnections, ^uint32(0))
  30. }
  31. func (s *Stats) addIncomingTraffic(n int) {
  32. atomic.AddUint64(&s.Traffic.Incoming, uint64(n))
  33. }
  34. func (s *Stats) addOutgoingTraffic(n int) {
  35. atomic.AddUint64(&s.Traffic.Outgoing, uint64(n))
  36. }
  37. func (s *Stats) Serve(host net.IP, port uint16) {
  38. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  39. w.Header().Set("Content-Type", "application/json")
  40. json.NewEncoder(w).Encode(s)
  41. })
  42. addr := net.JoinHostPort(host.String(), strconv.Itoa(int(port)))
  43. http.ListenAndServe(addr, nil)
  44. }
  45. func NewStats() *Stats {
  46. return &Stats{Uptime: statsUptime(time.Now())}
  47. }