Permalink
Browse files

Don't call os.Hostname on every single call

The hostname doesn't change, so we can store it in a global variable
and use the variable to add it to our list of tags
  • Loading branch information...
prashantv committed Jan 21, 2016
1 parent 303faea commit a8c6b0e1cd043df85ccbc57883c6422863176c17
Showing with 16 additions and 6 deletions.
  1. +16 −6 handlers/stats_handler.go
View
@@ -14,6 +14,8 @@ import (
const serviceName = "demo-app"
var _hostName = getHost()
// WithStats wraps handlers with stats reporting. It tracks metrics such
// as the number of requests per endpoint, the latency, etc.
func WithStats(h http.HandlerFunc) http.HandlerFunc {
@@ -29,19 +31,27 @@ func WithStats(h http.HandlerFunc) http.HandlerFunc {
}
}
func getHost() string {
host, err := os.Hostname()
if err != nil {
return ""
}
if idx := strings.IndexByte(host, '.'); idx > 0 {
host = host[:idx]
}
return host
}
func getStatsTags(r *http.Request) map[string]string {
userBrowser, userOS := parseUserAgent(r.UserAgent())
stats := map[string]string{
"browser": userBrowser,
"os": userOS,
"endpoint": filepath.Base(r.URL.Path),
}
host, err := os.Hostname()
if err == nil {
if idx := strings.IndexByte(host, '.'); idx > 0 {
host = host[:idx]
}
stats["host"] = host
if _hostName != "" {
stats["host"] = _hostName
}
return stats
}

0 comments on commit a8c6b0e

Please sign in to comment.