-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcaas.go
102 lines (86 loc) · 2.26 KB
/
caas.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Counter struct {
Name string `json:"name"`
Value int64 `json:"count"`
Host string `json:"host"`
DBStats []QueryStat `json:"dbStats""`
}
type QueryStat struct {
Statement string `json:"statement"`
Attempts int `json:"attempts"`
Time string `json:"time"`
Host string `json:"host"`
Rows int `json:"rows"`
}
var db DB
func Get(w http.ResponseWriter, r *http.Request, renderer func(w http.ResponseWriter, counter Counter)) {
vars := mux.Vars(r)
name := vars["counter_name"]
log.Printf("Processing request for counter %q", name)
counter, err := db.IncrementAndGet(name)
if err != nil {
log.Printf("Error incrementing counter %q: %s", name, err)
w.WriteHeader(http.StatusInternalServerError)
errJson := fmt.Sprintf("{\"error\": \"%s\"}\n", err)
w.Write([]byte(errJson))
return
}
log.Printf("Counter %q bumped to %+v", name, counter)
w.WriteHeader(http.StatusOK)
renderer(w, counter)
}
func jsonRenderer(w http.ResponseWriter, counter Counter) {
json.NewEncoder(w).Encode(counter)
}
func htmlRenderer(w http.ResponseWriter, counter Counter) {
t := `
<html>
<head><title>{{.Name}}</title></head>
<body>
<h1>Counter: {{.Name}}, value: {{.Value}}</h1>
<pre>
Web server: {{.Host}}
Queries:
{{range .DBStats}}
DB server: {{.Host}}
Query: {{.Statement}}
Attempts: {{.Attempts}}
Time: {{.Time}}
{{end}}
</pre>
</body>
</html>`
template.Must(template.New("html").Parse(t)).Execute(w, counter)
}
func GetJSON(w http.ResponseWriter, r *http.Request) {
Get(w, r, jsonRenderer)
}
func GetHTML(w http.ResponseWriter, r *http.Request) {
Get(w, r, htmlRenderer)
}
func Redirect(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Location", "sample/html")
w.WriteHeader(http.StatusPermanentRedirect)
w.Write([]byte("use /<counter>/<html>\n"))
}
func main() {
var err error
db, err = NewCassandra()
if err != nil {
panic(err)
}
fmt.Println("cassandra init done")
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Redirect)
router.HandleFunc("/{counter_name}/json", GetJSON)
router.HandleFunc("/{counter_name}/html", GetHTML)
log.Fatal(http.ListenAndServe(":80", router))
}