blob: 58d66f2547108f29c8e0c804905c5759e5e0cd73 [file] [log] [blame]
Jude Cross638c4ef2017-07-24 14:57:20 -07001package main
2
3import (
4 "flag"
5 "fmt"
6 "io"
7 "net/http"
8 "sync"
9 "time"
10)
11
12var sess_cookie http.Cookie
13var resp string
14
15type ConnectionCount struct {
16 mu sync.Mutex
17 cur_conn int
18 max_conn int
19 total_conn int
20}
21
22var scoreboard ConnectionCount
23
24func (cc *ConnectionCount) open() {
25 cc.mu.Lock()
26 defer cc.mu.Unlock()
27
28 cc.cur_conn++
29 cc.total_conn++
30}
31
32func (cc *ConnectionCount) close() {
33 cc.mu.Lock()
34 defer cc.mu.Unlock()
35
36 if cc.cur_conn > cc.max_conn {
37 cc.max_conn = cc.cur_conn
38 }
39 cc.cur_conn--
40}
41
42func (cc *ConnectionCount) stats() (int, int) {
43 cc.mu.Lock()
44 defer cc.mu.Unlock()
45
46 return cc.max_conn, cc.total_conn
47}
48
49func (cc *ConnectionCount) reset() {
50 cc.mu.Lock()
51 defer cc.mu.Unlock()
52
53 cc.max_conn = 0
54 cc.total_conn = 0
55}
56
57func root_handler(w http.ResponseWriter, r *http.Request) {
58 scoreboard.open()
59 defer scoreboard.close()
60
61 http.SetCookie(w, &sess_cookie)
62 io.WriteString(w, resp)
63}
64
65func slow_handler(w http.ResponseWriter, r *http.Request) {
66 scoreboard.open()
67 defer scoreboard.close()
68
69 delay, err := time.ParseDuration(r.URL.Query().Get("delay"))
70 if err != nil {
71 delay = 3 * time.Second
72 }
73
74 time.Sleep(delay)
75 http.SetCookie(w, &sess_cookie)
76 io.WriteString(w, resp)
77}
78
79func stats_handler(w http.ResponseWriter, r *http.Request) {
80 http.SetCookie(w, &sess_cookie)
81 max_conn, total_conn := scoreboard.stats()
82 fmt.Fprintf(w, "max_conn=%d\ntotal_conn=%d\n", max_conn, total_conn)
83}
84
85func reset_handler(w http.ResponseWriter, r *http.Request) {
86 http.SetCookie(w, &sess_cookie)
87 scoreboard.reset()
88 fmt.Fprintf(w, "reset\n")
89}
90
91func main() {
92 portPtr := flag.Int("port", 8080, "TCP port to listen on")
93 idPtr := flag.String("id", "1", "Server ID")
94
95 flag.Parse()
96
97 resp = fmt.Sprintf("%s", *idPtr)
Michael Johnsonb7069872018-01-09 17:15:31 -080098 sess_cookie.Name = "JSESSIONID"
Jude Cross638c4ef2017-07-24 14:57:20 -070099 sess_cookie.Value = *idPtr
100
101 http.HandleFunc("/", root_handler)
102 http.HandleFunc("/slow", slow_handler)
103 http.HandleFunc("/stats", stats_handler)
104 http.HandleFunc("/reset", reset_handler)
105 portStr := fmt.Sprintf(":%d", *portPtr)
106 http.ListenAndServe(portStr, nil)
107}