forked from pibigstar/go-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (48 loc) · 1.04 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"time"
"github.com/varstr/uaparser"
)
const hostPort = ":8080"
func main() {
http.HandleFunc("/hello", Hello)
fmt.Println("Starting server on", hostPort)
if err := http.ListenAndServe(hostPort, nil); err != nil {
log.Fatalf("HTTP server failed: %v", err)
}
}
func Hello(w http.ResponseWriter, r *http.Request) {
start := time.Now()
tags := getStatsTags(r)
duration := time.Since(start)
fmt.Println(tags, duration)
}
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),
}
hostName, _ := os.Hostname()
if hostName != "" {
stats["host"] = hostName
}
return stats
}
func parseUserAgent(uaString string) (browser, os string) {
ua := uaparser.Parse(uaString)
if ua.Browser != nil {
browser = ua.Browser.Name
}
if ua.OS != nil {
os = ua.OS.Name
}
return browser, os
}