1
0
Fork 0
mirror of https://github.com/Luzifer/mondash.git synced 2024-11-10 00:20:02 +00:00
mondash/main.go

80 lines
1.8 KiB
Go
Raw Normal View History

2015-02-07 18:32:44 +00:00
package main
import (
"crypto/md5"
"fmt"
"io/ioutil"
"net/http"
"time"
2015-07-06 19:41:21 +00:00
"github.com/Luzifer/mondash/config"
"github.com/Luzifer/mondash/storage"
2015-02-07 18:32:44 +00:00
"github.com/flosch/pongo2"
"github.com/gorilla/mux"
2015-02-07 18:32:44 +00:00
_ "github.com/flosch/pongo2-addons"
)
2015-07-06 19:41:21 +00:00
var (
templates = make(map[string]*pongo2.Template)
store storage.Storage
cfg *config.Config
)
2015-02-07 18:32:44 +00:00
func main() {
preloadTemplates()
2015-07-06 19:41:21 +00:00
var err error
cfg = config.Load()
store, err = storage.GetStorage(cfg)
if err != nil {
2015-07-06 19:41:21 +00:00
fmt.Printf("An error occurred while loading the storage handler: %s", err)
}
2015-02-07 18:32:44 +00:00
r := mux.NewRouter()
r.HandleFunc("/", handleRedirectWelcome).
Methods("GET")
r.HandleFunc("/create", handleCreateRandomDashboard).
Methods("GET")
r.HandleFunc("/{dashid}", handleDisplayDashboard).
Methods("GET")
2015-02-07 18:32:44 +00:00
r.HandleFunc("/{dashid}/{metricid}", handlePutMetric).
Methods("PUT")
2015-02-07 18:32:44 +00:00
r.HandleFunc("/{dashid}", handleDeleteDashboard).
Methods("DELETE")
r.HandleFunc("/{dashid}/{metricid}", handleDeleteMetric).
Methods("DELETE")
2015-02-07 18:32:44 +00:00
2015-07-06 19:41:21 +00:00
go runWelcomePage(cfg)
2015-02-07 18:32:44 +00:00
http.Handle("/", r)
http.ListenAndServe(cfg.Listen, nil)
2015-02-07 18:32:44 +00:00
}
func generateAPIKey() string {
t := time.Now().String()
sum := md5.Sum([]byte(t))
return fmt.Sprintf("%x", sum)
}
func renderTemplate(templateName string, context pongo2.Context, res http.ResponseWriter) {
if tpl, ok := templates[templateName]; ok {
2015-02-20 18:47:36 +00:00
_ = tpl.ExecuteWriter(context, res)
2015-02-07 18:32:44 +00:00
} else {
res.WriteHeader(http.StatusInternalServerError)
2015-02-20 18:47:36 +00:00
_, _ = res.Write([]byte(fmt.Sprintf("Template %s not found!", templateName)))
2015-02-07 18:32:44 +00:00
}
}
func preloadTemplates() {
templateNames, err := ioutil.ReadDir("templates")
if err != nil {
panic("Templates directory not available!")
}
for _, tplname := range templateNames {
templates[tplname.Name()] = pongo2.Must(pongo2.FromFile(fmt.Sprintf("templates/%s", tplname.Name())))
}
}