Rework stats server

This commit is contained in:
9seconds
2018-10-16 22:17:46 +03:00
parent 7c463851b2
commit c74e0ee359
6 changed files with 169 additions and 178 deletions
+5 -35
View File
@@ -3,45 +3,19 @@ package stats
import (
"encoding/json"
"net/http"
"sync"
"time"
"go.uber.org/zap"
"github.com/9seconds/mtg/config"
)
var instance *stats
// Start starts new statistics server.
func Start(conf *config.Config) error {
func startServer(conf *config.Config) {
log := zap.S().Named("stats")
instance = &stats{
URLs: conf.GetURLs(),
Uptime: uptime(time.Now()),
mutex: &sync.RWMutex{},
}
if conf.StatsD.Enabled {
client, err := newStatsd(conf)
if err != nil {
return err
}
go client.run()
}
go crashManager()
go connectionManager()
go trafficManager()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
instance.mutex.Lock()
first, err := json.Marshal(instance)
instance.mutex.Unlock()
first, err := json.Marshal(GetStats())
if err != nil {
log.Errorw("Cannot encode json", "error", err)
http.Error(w, "Internal server error", 500)
@@ -59,11 +33,7 @@ func Start(conf *config.Config) error {
}
})
go func() {
if err := http.ListenAndServe(conf.StatAddr(), nil); err != nil {
log.Fatalw("Stats server has been stopped", "error", err)
}
}()
return nil
if err := http.ListenAndServe(conf.StatAddr(), nil); err != nil {
log.Fatalw("Stats server has been stopped", "error", err)
}
}