github.com/packtpublishing/learning-functional-programming-in-go@v0.0.0-20230130084745-8b849f6d58c4/Chapter05/02_decorator/src/easy_metrics/metrics.go (about)

     1  package easy_metrics
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"net/http"
     7  	"time"
     8  	"github.com/admobi/easy-metrics"
     9  	"decorator"
    10  )
    11  
    12  var (
    13  	avgResponseTime = metrics.NewGauge("avgResponseTime")
    14  	requests        = metrics.NewCounter("requests")
    15  	responseTime    = &timing{}
    16  )
    17  
    18  func Serve(addr string) error {
    19  	r, err := metrics.NewTrackRegistry("Stats", 100, time.Second, false)
    20  	if err != nil {
    21  		decorator.Error.Println(err)
    22  	}
    23  
    24  	err = r.AddMetrics(requests, avgResponseTime)
    25  	if err != nil {
    26  		decorator.Error.Println(err)
    27  	}
    28  
    29  	http.HandleFunc("/", handler)
    30  	return http.ListenAndServe(addr, nil)
    31  }
    32  
    33  func handler(w http.ResponseWriter, r *http.Request) {
    34  	begin := time.Now()
    35  
    36  	work()
    37  
    38  	responseTime.Observe(time.Since(begin))
    39  	requests.Inc()
    40  }
    41  
    42  func DisplayResults(addr string) error {
    43  	decorator.Info.Printf("Go to http://%s/easy-metrics?show=Stats", addr)
    44  	return nil
    45  }
    46  
    47  type timing struct {
    48  	count int64
    49  	sum   time.Duration
    50  }
    51  
    52  func (t *timing) Observe(d time.Duration) {
    53  	t.count++
    54  	t.sum += d
    55  	avgResponseTime.Set(t.sum.Seconds() / float64(t.count))
    56  }
    57  
    58  func (t timing) String() string {
    59  	avg := time.Duration(t.sum.Nanoseconds() / t.count)
    60  	return fmt.Sprintf("\"%v\"", avg)
    61  }
    62  
    63  
    64  func work() {
    65  	randInt := rand.Intn(5000)
    66  	decorator.Debug.Printf("- randInt: %v", randInt)
    67  
    68  	workTime := time.Duration(randInt) * time.Millisecond
    69  	time.Sleep(workTime)
    70  }