forked from rach/pome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
73 lines (65 loc) · 1.96 KB
/
web.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/rach/pome/Godeps/_workspace/src/github.com/elazarl/go-bindata-assetfs"
"github.com/rach/pome/Godeps/_workspace/src/github.com/jmoiron/sqlx"
_ "github.com/rach/pome/Godeps/_workspace/src/github.com/lib/pq"
"io"
"log"
"net/http"
)
func metricsHandler(a *appContext, w http.ResponseWriter, r *http.Request) (int, error) {
js, err := json.Marshal(a.metrics)
if err != nil {
return 500, err
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return 200, nil
}
type appContext struct {
db *sqlx.DB
metrics *MetricList
}
type appHandler struct {
*appContext
H func(*appContext, http.ResponseWriter, *http.Request) (int, error)
}
func initWebServer(context *appContext, web_port int) {
http.Handle("/api/stats", appHandler{context, metricsHandler})
http.HandleFunc("/about", aliasHandler)
http.HandleFunc("/bloat/indexes", aliasHandler)
http.HandleFunc("/bloat/tables", aliasHandler)
http.Handle("/",
http.FileServer(
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: ""}))
http.ListenAndServe(fmt.Sprintf(":%d", web_port), nil)
}
func aliasHandler(rw http.ResponseWriter, req *http.Request) {
if bs, err := Asset("index.html"); err != nil {
rw.WriteHeader(http.StatusNotFound)
} else {
var reader = bytes.NewBuffer(bs)
io.Copy(rw, reader)
}
}
func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Updated to pass ah.appContext as a parameter to our handler type.
status, err := ah.H(ah.appContext, w, r)
if err != nil {
log.Printf("HTTP %d: %q", status, err)
switch status {
case http.StatusNotFound:
http.NotFound(w, r)
// And if we wanted a friendlier error page, we can
// now leverage our context instance - e.g.
// err := ah.renderTemplate(w, "http_404.tmpl", nil)
case http.StatusInternalServerError:
http.Error(w, http.StatusText(status), status)
default:
http.Error(w, http.StatusText(status), status)
}
}
}