Skip to content

Commit

Permalink
Refactor file organisation in web.go
Browse files Browse the repository at this point in the history
  • Loading branch information
layterz committed Jan 8, 2016
1 parent 524fef8 commit 73d12c0
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions web.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ import (
_ "github.com/rach/pome/Godeps/_workspace/src/github.com/lib/pq"
)

type appContext struct {
db *sqlx.DB
metrics *MetricList
}

type appHandler struct {
*appContext
H func(*appContext, http.ResponseWriter, *http.Request) (int, error)
}

func metricsHandler(a *appContext, w http.ResponseWriter, r *http.Request) (int, error) {
js, err := json.Marshal(a.metrics)
if err != nil {
Expand All @@ -24,36 +34,29 @@ func metricsHandler(a *appContext, w http.ResponseWriter, r *http.Request) (int,
return 200, nil
}

type appContext struct {
db *sqlx.DB
metrics *MetricList
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)
}
}

type appHandler struct {
*appContext
H func(*appContext, http.ResponseWriter, *http.Request) (int, error)
func NewStaticHandler() http.Handler {
fs := assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: ""}
return http.FileServer(&fs)
}

func initWebServer(context *appContext, webPort 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.Handle("/", NewStaticHandler())
http.ListenAndServe(fmt.Sprintf(":%d", webPort), 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)
Expand Down

0 comments on commit 73d12c0

Please sign in to comment.