From 2310f06f8053721a226cc0837d66c7b5006d2e76 Mon Sep 17 00:00:00 2001 From: Hunter Long Date: Sun, 16 Sep 2018 00:48:34 -0700 Subject: [PATCH] time to UTC - timezone added - comments - remove unused - lint --- cmd/main_test.go | 56 +++++++++---------- core/core.go | 8 +++ core/core_test.go | 4 -- core/database.go | 2 +- core/failures.go | 1 + core/hits.go | 1 + core/notifier/notifiers.go | 2 +- core/services.go | 8 ++- handlers/api.go | 28 +++++----- handlers/api_handlers_test.go | 4 +- handlers/benchmark_test.go | 4 +- handlers/dashboard.go | 22 ++++---- handlers/handlers.go | 11 ++-- handlers/index.go | 8 +-- handlers/plugins.go | 4 +- handlers/prometheus.go | 2 +- handlers/routes.go | 100 +++++++++++++++++----------------- handlers/services.go | 38 ++++++------- handlers/settings.go | 31 ++++++----- handlers/setup.go | 18 +++--- handlers/users.go | 18 +++--- notifiers/discord.go | 7 +-- notifiers/discord_test.go | 5 +- notifiers/email_test.go | 5 +- notifiers/slack_test.go | 5 +- notifiers/twilio.go | 18 +++--- notifiers/twilio_test.go | 5 +- source/tmpl/settings.html | 37 +++++++++++++ types/failure.go | 2 + types/service.go | 39 ------------- utils/utils.go | 23 +++++++- utils/utils_test.go | 16 +++++- 32 files changed, 282 insertions(+), 250 deletions(-) diff --git a/cmd/main_test.go b/cmd/main_test.go index caec2baa..da043787 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -113,7 +113,7 @@ func TestRunAll(t *testing.T) { RunSelectAllNotifiers(t) }) t.Run(dbt+" Create Users", func(t *testing.T) { - RunUser_Create(t) + RunUserCreate(t) }) t.Run(dbt+" Update User", func(t *testing.T) { RunUser_Update(t) @@ -123,52 +123,52 @@ func TestRunAll(t *testing.T) { RunUser_NonUniqueCreate(t) }) t.Run(dbt+" Select Users", func(t *testing.T) { - RunUser_SelectAll(t) + RunUserSelectAll(t) }) t.Run(dbt+" Select Services", func(t *testing.T) { RunSelectAllServices(t) }) t.Run(dbt+" Select One Service", func(t *testing.T) { - RunOneService_Check(t) + RunOneServiceCheck(t) }) t.Run(dbt+" Create Service", func(t *testing.T) { - RunService_Create(t) + RunServiceCreate(t) }) t.Run(dbt+" Create Hits", func(t *testing.T) { - RunCreateService_Hits(t) + RunCreateServiceHits(t) }) t.Run(dbt+" Service ToJSON()", func(t *testing.T) { - RunService_ToJSON(t) + RunServiceToJSON(t) }) t.Run(dbt+" Avg Time", func(t *testing.T) { RunService_AvgTime(t) }) t.Run(dbt+" Online 24h", func(t *testing.T) { - RunService_Online24(t) + RunServiceOnline24(t) }) t.Run(dbt+" Chart Data", func(t *testing.T) { - RunService_GraphData(t) + RunServiceGraphData(t) }) t.Run(dbt+" Create Failing Service", func(t *testing.T) { - RunBadService_Create(t) + RunBadServiceCreate(t) }) t.Run(dbt+" Check Bad Service", func(t *testing.T) { - RunBadService_Check(t) + RunBadServiceCheck(t) }) t.Run(dbt+" Select Hits", func(t *testing.T) { - RunService_Hits(t) + RunServiceHits(t) }) t.Run(dbt+" Select Failures", func(t *testing.T) { - RunService_Failures(t) + RunServiceFailures(t) }) t.Run(dbt+" Select Limited Hits", func(t *testing.T) { - RunService_LimitedHits(t) + RunServiceLimitedHits(t) }) t.Run(dbt+" Delete Service", func(t *testing.T) { RunDeleteService(t) }) t.Run(dbt+" Delete User", func(t *testing.T) { - RunUser_Delete(t) + RunUserDelete(t) }) t.Run(dbt+" HTTP /", func(t *testing.T) { RunIndexHandler(t) @@ -301,13 +301,13 @@ func RunSelectAllNotifiers(t *testing.T) { assert.Equal(t, 5, len(core.CoreApp.Notifications)) } -func RunUser_SelectAll(t *testing.T) { +func RunUserSelectAll(t *testing.T) { users, err := core.SelectAllUsers() assert.Nil(t, err) assert.Equal(t, 4, len(users)) } -func RunUser_Create(t *testing.T) { +func RunUserCreate(t *testing.T) { user := core.ReturnUser(&types.User{ Username: "hunterlong", Password: "password123", @@ -350,7 +350,7 @@ func RunUser_NonUniqueCreate(t *testing.T) { assert.Nil(t, admin) } -func RunUser_Delete(t *testing.T) { +func RunUserDelete(t *testing.T) { user, err := core.SelectUser(2) assert.Nil(t, err) assert.NotNil(t, user) @@ -368,13 +368,13 @@ func RunSelectAllServices(t *testing.T) { } } -func RunOneService_Check(t *testing.T) { +func RunOneServiceCheck(t *testing.T) { service := core.SelectService(1) assert.NotNil(t, service) assert.Equal(t, "Google", service.Name) } -func RunService_Create(t *testing.T) { +func RunServiceCreate(t *testing.T) { service := core.ReturnService(&types.Service{ Name: "test service", Domain: "https://google.com", @@ -390,7 +390,7 @@ func RunService_Create(t *testing.T) { assert.Equal(t, int64(16), id) } -func RunService_ToJSON(t *testing.T) { +func RunServiceToJSON(t *testing.T) { service := core.SelectService(1) assert.NotNil(t, service) jsoned := service.ToJSON() @@ -404,7 +404,7 @@ func RunService_AvgTime(t *testing.T) { assert.Equal(t, "100", avg) } -func RunService_Online24(t *testing.T) { +func RunServiceOnline24(t *testing.T) { var dayAgo = time.Now().Add(-24 * time.Hour).Add(-10 * time.Minute) service := core.SelectService(1) @@ -428,7 +428,7 @@ func RunService_Online24(t *testing.T) { assert.True(t, online > float32(49.00)) } -func RunService_GraphData(t *testing.T) { +func RunServiceGraphData(t *testing.T) { service := core.SelectService(1) assert.NotNil(t, service) data := service.GraphData() @@ -438,7 +438,7 @@ func RunService_GraphData(t *testing.T) { assert.NotEmpty(t, data) } -func RunBadService_Create(t *testing.T) { +func RunBadServiceCreate(t *testing.T) { service := core.ReturnService(&types.Service{ Name: "Bad Service", Domain: "https://9839f83h72gey2g29278hd2od2d.com", @@ -454,7 +454,7 @@ func RunBadService_Create(t *testing.T) { assert.Equal(t, int64(17), id) } -func RunBadService_Check(t *testing.T) { +func RunBadServiceCheck(t *testing.T) { service := core.SelectService(17) assert.NotNil(t, service) assert.Equal(t, "Bad Service", service.Name) @@ -474,7 +474,7 @@ func RunDeleteService(t *testing.T) { assert.Nil(t, err) } -func RunCreateService_Hits(t *testing.T) { +func RunCreateServiceHits(t *testing.T) { services := core.CoreApp.Services assert.NotNil(t, services) assert.Equal(t, 16, len(services)) @@ -484,7 +484,7 @@ func RunCreateService_Hits(t *testing.T) { } } -func RunService_Hits(t *testing.T) { +func RunServiceHits(t *testing.T) { service := core.SelectService(1) assert.NotNil(t, service) hits, err := service.Hits() @@ -492,14 +492,14 @@ func RunService_Hits(t *testing.T) { assert.NotZero(t, len(hits)) } -func RunService_Failures(t *testing.T) { +func RunServiceFailures(t *testing.T) { service := core.SelectService(17) assert.NotNil(t, service) assert.Equal(t, "Bad Service", service.Name) assert.NotEmpty(t, service.AllFailures()) } -func RunService_LimitedHits(t *testing.T) { +func RunServiceLimitedHits(t *testing.T) { service := core.SelectService(1) assert.NotNil(t, service) hits, err := service.LimitedHits() diff --git a/core/core.go b/core/core.go index e2e4e257..ca11e8f7 100644 --- a/core/core.go +++ b/core/core.go @@ -81,6 +81,14 @@ func UpdateCore(c *Core) (*Core, error) { return c, db.Error } +// UsingAssets will return true if /assets folder is present +func (c Core) CurrentTime() string { + t := time.Now().UTC() + current := utils.Timezoner(t, c.Timezone) + ansic := "Monday 03:04:05 PM" + return current.Format(ansic) +} + // UsingAssets will return true if /assets folder is present func (c Core) UsingAssets() bool { return source.UsingAssets(utils.Directory) diff --git a/core/core_test.go b/core/core_test.go index 6c69ef49..5d4112e3 100644 --- a/core/core_test.go +++ b/core/core_test.go @@ -27,10 +27,6 @@ var ( dir string ) -const ( - SERVICE_SINCE = "2018-08-30T10:42:08-07:00" // "2006-01-02T15:04:05Z07:00" -) - func init() { dir = utils.Directory utils.InitLogs() diff --git a/core/database.go b/core/database.go index 5ee06b53..4754d962 100644 --- a/core/database.go +++ b/core/database.go @@ -116,7 +116,7 @@ func (db *DbConfig) Connect(retry bool, location string) error { Configs.DbPort = 3306 } host := fmt.Sprintf("%v:%v", Configs.DbHost, Configs.DbPort) - conn = fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8&parseTime=True&loc=Local", Configs.DbUser, Configs.DbPass, host, Configs.DbData) + conn = fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8&parseTime=True&loc=UTC", Configs.DbUser, Configs.DbPass, host, Configs.DbData) case "postgres": if Configs.DbPort == 0 { Configs.DbPort = 5432 diff --git a/core/failures.go b/core/failures.go index 669c598e..74f0f0d7 100644 --- a/core/failures.go +++ b/core/failures.go @@ -30,6 +30,7 @@ type Failure struct { // CreateFailure will create a new failure record for a service func (s *Service) CreateFailure(f *types.Failure) (int64, error) { + f.CreatedAt = time.Now().UTC() f.Service = s.Id s.Failures = append(s.Failures, f) row := failuresDB().Create(f) diff --git a/core/hits.go b/core/hits.go index 67d5d5f2..2d241191 100644 --- a/core/hits.go +++ b/core/hits.go @@ -27,6 +27,7 @@ type Hit struct { // CreateHit will create a new 'hit' record in the database for a successful/online service func (s *Service) CreateHit(h *types.Hit) (int64, error) { + h.CreatedAt = time.Now().UTC() db := hitsDB().Create(h) if db.Error != nil { utils.Log(2, db.Error) diff --git a/core/notifier/notifiers.go b/core/notifier/notifiers.go index 42572652..2b309b57 100644 --- a/core/notifier/notifiers.go +++ b/core/notifier/notifiers.go @@ -347,7 +347,7 @@ func (n *Notification) GetValue(dbField string) string { case "api_secret": return n.ApiSecret case "limits": - return utils.IntString(int(n.Limits)) + return utils.ToString(int(n.Limits)) } return "" } diff --git a/core/services.go b/core/services.go index e9626216..3757addc 100644 --- a/core/services.go +++ b/core/services.go @@ -136,16 +136,17 @@ func (s *Service) lastFailure() *Failure { func (s *Service) SmallText() string { last := s.LimitedFailures() hits, _ := s.LimitedHits() + zone := CoreApp.Timezone if s.Online { if len(last) == 0 { - return fmt.Sprintf("Online since %v", s.CreatedAt.Format("Monday 3:04PM, Jan _2 2006")) + return fmt.Sprintf("Online since %v", utils.Timezoner(s.CreatedAt, zone).Format("Monday 3:04:05PM, Jan _2 2006")) } else { - return fmt.Sprintf("Online, last failure was %v", hits[0].CreatedAt.Format("Monday 3:04PM, Jan _2 2006")) + return fmt.Sprintf("Online, last failure was %v", utils.Timezoner(hits[0].CreatedAt, zone).Format("Monday 3:04:05PM, Jan _2 2006")) } } if len(last) > 0 { lastFailure := s.lastFailure() - return fmt.Sprintf("%v on %v", lastFailure.ParseError(), last[0].CreatedAt.Format("Monday 3:04PM, Jan _2 2006")) + return fmt.Sprintf("%v on %v", lastFailure.ParseError(), utils.Timezoner(last[0].CreatedAt, zone).Format("Monday 3:04:05PM, Jan _2 2006")) } else { return fmt.Sprintf("%v is currently offline", s.Name) } @@ -186,6 +187,7 @@ func (s *Service) GraphDataRaw() []*DateScan { if err != nil { utils.Log(2, fmt.Sprintf("Issue parsing time %v", err)) } + gd.CreatedAt = utils.Timezoner(gd.CreatedAt, CoreApp.Timezone) gd.Value = int64(ff) d = append(d, gd) } diff --git a/handlers/api.go b/handlers/api.go index fa502b80..12e8eddd 100644 --- a/handlers/api.go +++ b/handlers/api.go @@ -32,7 +32,7 @@ type ApiResponse struct { Method string `json:"method"` } -func ApiIndexHandler(w http.ResponseWriter, r *http.Request) { +func apiIndexHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -50,7 +50,7 @@ func ApiIndexHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(out) } -func ApiRenewHandler(w http.ResponseWriter, r *http.Request) { +func apiRenewHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -65,7 +65,7 @@ func ApiRenewHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/settings", http.StatusSeeOther) } -func ApiCheckinHandler(w http.ResponseWriter, r *http.Request) { +func apiCheckinHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -77,7 +77,7 @@ func ApiCheckinHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(checkin) } -func ApiServiceHandler(w http.ResponseWriter, r *http.Request) { +func apiServiceHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -93,7 +93,7 @@ func ApiServiceHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(service) } -func ApiServiceDataHandler(w http.ResponseWriter, r *http.Request) { +func apiServiceDataHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -109,7 +109,7 @@ func ApiServiceDataHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(service.GraphDataRaw()) } -func ApiCreateServiceHandler(w http.ResponseWriter, r *http.Request) { +func apiCreateServiceHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -131,7 +131,7 @@ func ApiCreateServiceHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(service) } -func ApiServiceUpdateHandler(w http.ResponseWriter, r *http.Request) { +func apiServiceUpdateHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -157,7 +157,7 @@ func ApiServiceUpdateHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(service) } -func ApiServiceDeleteHandler(w http.ResponseWriter, r *http.Request) { +func apiServiceDeleteHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -183,7 +183,7 @@ func ApiServiceDeleteHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(output) } -func ApiAllServicesHandler(w http.ResponseWriter, r *http.Request) { +func apiAllServicesHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -199,7 +199,7 @@ func ApiAllServicesHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(services) } -func ApiUserHandler(w http.ResponseWriter, r *http.Request) { +func apiUserHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -214,7 +214,7 @@ func ApiUserHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } -func ApiUserUpdateHandler(w http.ResponseWriter, r *http.Request) { +func apiUserUpdateHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -239,7 +239,7 @@ func ApiUserUpdateHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } -func ApiUserDeleteHandler(w http.ResponseWriter, r *http.Request) { +func apiUserDeleteHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -265,7 +265,7 @@ func ApiUserDeleteHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(output) } -func ApiAllUsersHandler(w http.ResponseWriter, r *http.Request) { +func apiAllUsersHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -275,7 +275,7 @@ func ApiAllUsersHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(users) } -func ApiCreateUsersHandler(w http.ResponseWriter, r *http.Request) { +func apiCreateUsersHandler(w http.ResponseWriter, r *http.Request) { if !isAPIAuthorized(r) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return diff --git a/handlers/api_handlers_test.go b/handlers/api_handlers_test.go index a848236e..f6000418 100644 --- a/handlers/api_handlers_test.go +++ b/handlers/api_handlers_test.go @@ -30,9 +30,7 @@ import ( ) const ( - NEW_HTTP_SERVICE = `{"name": "Google Website", "domain": "https://google.com", "expected_status": 200, "check_interval": 10, "type": "http", "method": "GET"}` - UPDATED_HTTP_SERVICE = `{"id": 1, name": "Google Website", "domain": "https://google.com", "expected_status": 200, "check_interval": 10, "type": "http", "method": "GET"}` - NEW_TCP_SERVICE = `{"name": "Google DNS", "domain": "8.8.8.8", "expected": "", "check_interval": 5, "type": "tcp"}` + NEW_HTTP_SERVICE = `{"name": "Google Website", "domain": "https://google.com", "expected_status": 200, "check_interval": 10, "type": "http", "method": "GET"}` ) var ( diff --git a/handlers/benchmark_test.go b/handlers/benchmark_test.go index 2107bb99..cdec7e78 100644 --- a/handlers/benchmark_test.go +++ b/handlers/benchmark_test.go @@ -26,7 +26,7 @@ func BenchmarkHandleIndex(b *testing.B) { r := request(b, "/") for i := 0; i < b.N; i++ { rw := httptest.NewRecorder() - IndexHandler(rw, r) + indexHandler(rw, r) } } @@ -34,7 +34,7 @@ func BenchmarkServicesHandlerIndex(b *testing.B) { r := request(b, "/") for i := 0; i < b.N; i++ { rw := httptest.NewRecorder() - ServicesHandler(rw, r) + servicesHandler(rw, r) } } diff --git a/handlers/dashboard.go b/handlers/dashboard.go index 6fa3d12c..b6fb7d48 100644 --- a/handlers/dashboard.go +++ b/handlers/dashboard.go @@ -23,17 +23,17 @@ import ( "net/http" ) -func DashboardHandler(w http.ResponseWriter, r *http.Request) { +func dashboardHandler(w http.ResponseWriter, r *http.Request) { fmt.Println() if !IsAuthenticated(r) { err := core.ErrorResponse{} - ExecuteResponse(w, r, "login.html", err, nil) + executeResponse(w, r, "login.html", err, nil) } else { - ExecuteResponse(w, r, "dashboard.html", core.CoreApp, nil) + executeResponse(w, r, "dashboard.html", core.CoreApp, nil) } } -func LoginHandler(w http.ResponseWriter, r *http.Request) { +func loginHandler(w http.ResponseWriter, r *http.Request) { if Store == nil { resetCookies() } @@ -49,27 +49,27 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/dashboard", http.StatusSeeOther) } else { err := core.ErrorResponse{Error: "Incorrect login information submitted, try again."} - ExecuteResponse(w, r, "login.html", err, nil) + executeResponse(w, r, "login.html", err, nil) } } -func LogoutHandler(w http.ResponseWriter, r *http.Request) { +func logoutHandler(w http.ResponseWriter, r *http.Request) { session, _ := Store.Get(r, COOKIE_KEY) session.Values["authenticated"] = false session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) } -func HelpHandler(w http.ResponseWriter, r *http.Request) { +func helpHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return } help := source.HelpMarkdown() - ExecuteResponse(w, r, "help.html", help, nil) + executeResponse(w, r, "help.html", help, nil) } -func LogsHandler(w http.ResponseWriter, r *http.Request) { +func logsHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -82,10 +82,10 @@ func LogsHandler(w http.ResponseWriter, r *http.Request) { logs = append(logs, utils.LastLines[i].FormatForHtml()+"\r\n") } utils.LockLines.Unlock() - ExecuteResponse(w, r, "logs.html", logs, nil) + executeResponse(w, r, "logs.html", logs, nil) } -func LogsLineHandler(w http.ResponseWriter, r *http.Request) { +func logsLineHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { w.WriteHeader(http.StatusInternalServerError) return diff --git a/handlers/handlers.go b/handlers/handlers.go index bcf27114..ccd16c9e 100644 --- a/handlers/handlers.go +++ b/handlers/handlers.go @@ -82,7 +82,7 @@ func IsAuthenticated(r *http.Request) bool { return session.Values["authenticated"].(bool) } -func ExecuteResponse(w http.ResponseWriter, r *http.Request, file string, data interface{}, redirect interface{}) { +func executeResponse(w http.ResponseWriter, r *http.Request, file string, data interface{}, redirect interface{}) { utils.Http(r) if url, ok := redirect.(string); ok { http.Redirect(w, r, url, http.StatusSeeOther) @@ -144,6 +144,9 @@ func ExecuteResponse(w http.ResponseWriter, r *http.Request, file string, data i "Error": func() string { return "" }, + "ToString": func(v interface{}) string { + return utils.ToString(v) + }, }) t, err = t.Parse(nav) if err != nil { @@ -163,7 +166,7 @@ func ExecuteResponse(w http.ResponseWriter, r *http.Request, file string, data i } } -func ExecuteJSResponse(w http.ResponseWriter, r *http.Request, file string, data interface{}) { +func executeJSResponse(w http.ResponseWriter, r *http.Request, file string, data interface{}) { render, err := source.JsBox.String(file) if err != nil { utils.Log(4, err) @@ -178,9 +181,9 @@ func ExecuteJSResponse(w http.ResponseWriter, r *http.Request, file string, data t.Execute(w, data) } -func Error404Handler(w http.ResponseWriter, r *http.Request) { +func error404Handler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) - ExecuteResponse(w, r, "error_404.html", nil, nil) + executeResponse(w, r, "error_404.html", nil, nil) } type DbConfig types.DbConfig diff --git a/handlers/index.go b/handlers/index.go index b3356dc0..63b30f43 100644 --- a/handlers/index.go +++ b/handlers/index.go @@ -26,16 +26,16 @@ type index struct { Core *core.Core } -func IndexHandler(w http.ResponseWriter, r *http.Request) { +func indexHandler(w http.ResponseWriter, r *http.Request) { if core.Configs == nil { http.Redirect(w, r, "/setup", http.StatusSeeOther) return } - ExecuteResponse(w, r, "index.html", core.CoreApp, nil) + executeResponse(w, r, "index.html", core.CoreApp, nil) } -func TrayHandler(w http.ResponseWriter, r *http.Request) { - ExecuteResponse(w, r, "tray.html", core.CoreApp, nil) +func trayHandler(w http.ResponseWriter, r *http.Request) { + executeResponse(w, r, "tray.html", core.CoreApp, nil) } func DesktopInit(ip string, port int) { diff --git a/handlers/plugins.go b/handlers/plugins.go index 7e3b4607..66771df2 100644 --- a/handlers/plugins.go +++ b/handlers/plugins.go @@ -26,7 +26,7 @@ type PluginSelect struct { Params map[string]interface{} } -func PluginSavedHandler(w http.ResponseWriter, r *http.Request) { +func pluginSavedHandler(w http.ResponseWriter, r *http.Request) { auth := IsAuthenticated(r) if !auth { http.Redirect(w, r, "/", http.StatusSeeOther) @@ -43,7 +43,7 @@ func PluginSavedHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/settings", http.StatusSeeOther) } -func PluginsDownloadHandler(w http.ResponseWriter, r *http.Request) { +func pluginsDownloadHandler(w http.ResponseWriter, r *http.Request) { auth := IsAuthenticated(r) if !auth { http.Redirect(w, r, "/", http.StatusSeeOther) diff --git a/handlers/prometheus.go b/handlers/prometheus.go index 923ccea6..3369b0ea 100644 --- a/handlers/prometheus.go +++ b/handlers/prometheus.go @@ -33,7 +33,7 @@ import ( // - targets: ['statup:8080'] // -func PrometheusHandler(w http.ResponseWriter, r *http.Request) { +func prometheusHandler(w http.ResponseWriter, r *http.Request) { utils.Log(1, fmt.Sprintf("Prometheus /metrics Request From IP: %v\n", r.RemoteAddr)) if !isAuthorized(r) { http.Redirect(w, r, "/", http.StatusSeeOther) diff --git a/handlers/routes.go b/handlers/routes.go index 2b3927f5..72607ed6 100644 --- a/handlers/routes.go +++ b/handlers/routes.go @@ -33,7 +33,7 @@ var ( func Router() *mux.Router { dir := utils.Directory r := mux.NewRouter() - r.Handle("/", http.HandlerFunc(IndexHandler)) + r.Handle("/", http.HandlerFunc(indexHandler)) if source.UsingAssets(dir) { indexHandler := http.FileServer(http.Dir(dir + "/assets/")) r.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir(dir+"/assets/css")))) @@ -47,61 +47,61 @@ func Router() *mux.Router { r.PathPrefix("/statup.png").Handler(http.FileServer(source.TmplBox.HTTPBox())) } r.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(source.JsBox.HTTPBox()))) - r.Handle("/charts.js", http.HandlerFunc(RenderServiceChartsHandler)) - r.Handle("/charts/{id}.js", http.HandlerFunc(RenderServiceChartHandler)) - r.Handle("/setup", http.HandlerFunc(SetupHandler)).Methods("GET") - r.Handle("/setup", http.HandlerFunc(ProcessSetupHandler)).Methods("POST") - r.Handle("/dashboard", http.HandlerFunc(DashboardHandler)).Methods("GET") - r.Handle("/dashboard", http.HandlerFunc(LoginHandler)).Methods("POST") - r.Handle("/logout", http.HandlerFunc(LogoutHandler)) - r.Handle("/services", http.HandlerFunc(ServicesHandler)).Methods("GET") - r.Handle("/services", http.HandlerFunc(CreateServiceHandler)).Methods("POST") - r.Handle("/services/reorder", http.HandlerFunc(ReorderServiceHandler)).Methods("POST") - r.Handle("/service/{id}", http.HandlerFunc(ServicesViewHandler)).Methods("GET") - r.Handle("/service/{id}", http.HandlerFunc(ServicesUpdateHandler)).Methods("POST") - r.Handle("/service/{id}/edit", http.HandlerFunc(ServicesViewHandler)) - r.Handle("/service/{id}/delete", http.HandlerFunc(ServicesDeleteHandler)) - r.Handle("/service/{id}/delete_failures", http.HandlerFunc(ServicesDeleteFailuresHandler)).Methods("GET") - r.Handle("/service/{id}/checkin", http.HandlerFunc(CheckinCreateUpdateHandler)).Methods("POST") - r.Handle("/users", http.HandlerFunc(UsersHandler)).Methods("GET") - r.Handle("/users", http.HandlerFunc(CreateUserHandler)).Methods("POST") - r.Handle("/user/{id}", http.HandlerFunc(UsersEditHandler)).Methods("GET") - r.Handle("/user/{id}", http.HandlerFunc(UpdateUserHandler)).Methods("POST") - r.Handle("/user/{id}/delete", http.HandlerFunc(UsersDeleteHandler)).Methods("GET") - r.Handle("/settings", http.HandlerFunc(SettingsHandler)).Methods("GET") - r.Handle("/settings", http.HandlerFunc(SaveSettingsHandler)).Methods("POST") - r.Handle("/settings/css", http.HandlerFunc(SaveSASSHandler)).Methods("POST") - r.Handle("/settings/build", http.HandlerFunc(SaveAssetsHandler)).Methods("GET") - r.Handle("/settings/delete_assets", http.HandlerFunc(DeleteAssetsHandler)).Methods("GET") - r.Handle("/settings/notifier/{method}", http.HandlerFunc(SaveNotificationHandler)).Methods("POST") - r.Handle("/plugins/download/{name}", http.HandlerFunc(PluginsDownloadHandler)) - r.Handle("/plugins/{name}/save", http.HandlerFunc(PluginSavedHandler)).Methods("POST") - r.Handle("/help", http.HandlerFunc(HelpHandler)) - r.Handle("/logs", http.HandlerFunc(LogsHandler)) - r.Handle("/logs/line", http.HandlerFunc(LogsLineHandler)) + r.Handle("/charts.js", http.HandlerFunc(renderServiceChartsHandler)) + r.Handle("/charts/{id}.js", http.HandlerFunc(renderServiceChartHandler)) + r.Handle("/setup", http.HandlerFunc(setupHandler)).Methods("GET") + r.Handle("/setup", http.HandlerFunc(processSetupHandler)).Methods("POST") + r.Handle("/dashboard", http.HandlerFunc(dashboardHandler)).Methods("GET") + r.Handle("/dashboard", http.HandlerFunc(loginHandler)).Methods("POST") + r.Handle("/logout", http.HandlerFunc(logoutHandler)) + r.Handle("/services", http.HandlerFunc(servicesHandler)).Methods("GET") + r.Handle("/services", http.HandlerFunc(createServiceHandler)).Methods("POST") + r.Handle("/services/reorder", http.HandlerFunc(reorderServiceHandler)).Methods("POST") + r.Handle("/service/{id}", http.HandlerFunc(servicesViewHandler)).Methods("GET") + r.Handle("/service/{id}", http.HandlerFunc(servicesUpdateHandler)).Methods("POST") + r.Handle("/service/{id}/edit", http.HandlerFunc(servicesViewHandler)) + r.Handle("/service/{id}/delete", http.HandlerFunc(servicesDeleteHandler)) + r.Handle("/service/{id}/delete_failures", http.HandlerFunc(servicesDeleteFailuresHandler)).Methods("GET") + r.Handle("/service/{id}/checkin", http.HandlerFunc(checkinCreateUpdateHandler)).Methods("POST") + r.Handle("/users", http.HandlerFunc(usersHandler)).Methods("GET") + r.Handle("/users", http.HandlerFunc(createUserHandler)).Methods("POST") + r.Handle("/user/{id}", http.HandlerFunc(usersEditHandler)).Methods("GET") + r.Handle("/user/{id}", http.HandlerFunc(updateUserHandler)).Methods("POST") + r.Handle("/user/{id}/delete", http.HandlerFunc(usersDeleteHandler)).Methods("GET") + r.Handle("/settings", http.HandlerFunc(settingsHandler)).Methods("GET") + r.Handle("/settings", http.HandlerFunc(saveSettingsHandler)).Methods("POST") + r.Handle("/settings/css", http.HandlerFunc(saveSASSHandler)).Methods("POST") + r.Handle("/settings/build", http.HandlerFunc(saveAssetsHandler)).Methods("GET") + r.Handle("/settings/delete_assets", http.HandlerFunc(deleteAssetsHandler)).Methods("GET") + r.Handle("/settings/notifier/{method}", http.HandlerFunc(saveNotificationHandler)).Methods("POST") + r.Handle("/plugins/download/{name}", http.HandlerFunc(pluginsDownloadHandler)) + r.Handle("/plugins/{name}/save", http.HandlerFunc(pluginSavedHandler)).Methods("POST") + r.Handle("/help", http.HandlerFunc(helpHandler)) + r.Handle("/logs", http.HandlerFunc(logsHandler)) + r.Handle("/logs/line", http.HandlerFunc(logsLineHandler)) // SERVICE API Routes - r.Handle("/api/services", http.HandlerFunc(ApiAllServicesHandler)).Methods("GET") - r.Handle("/api/services", http.HandlerFunc(ApiCreateServiceHandler)).Methods("POST") - r.Handle("/api/services/{id}", http.HandlerFunc(ApiServiceHandler)).Methods("GET") - r.Handle("/api/services/{id}/data", http.HandlerFunc(ApiServiceDataHandler)).Methods("GET") - r.Handle("/api/services/{id}", http.HandlerFunc(ApiServiceUpdateHandler)).Methods("POST") - r.Handle("/api/services/{id}", http.HandlerFunc(ApiServiceDeleteHandler)).Methods("DELETE") + r.Handle("/api/services", http.HandlerFunc(apiAllServicesHandler)).Methods("GET") + r.Handle("/api/services", http.HandlerFunc(apiCreateServiceHandler)).Methods("POST") + r.Handle("/api/services/{id}", http.HandlerFunc(apiServiceHandler)).Methods("GET") + r.Handle("/api/services/{id}/data", http.HandlerFunc(apiServiceDataHandler)).Methods("GET") + r.Handle("/api/services/{id}", http.HandlerFunc(apiServiceUpdateHandler)).Methods("POST") + r.Handle("/api/services/{id}", http.HandlerFunc(apiServiceDeleteHandler)).Methods("DELETE") // USER API Routes - r.Handle("/api/users", http.HandlerFunc(ApiAllUsersHandler)).Methods("GET") - r.Handle("/api/users", http.HandlerFunc(ApiCreateUsersHandler)).Methods("POST") - r.Handle("/api/users/{id}", http.HandlerFunc(ApiUserHandler)).Methods("GET") - r.Handle("/api/users/{id}", http.HandlerFunc(ApiUserUpdateHandler)).Methods("POST") - r.Handle("/api/users/{id}", http.HandlerFunc(ApiUserDeleteHandler)).Methods("DELETE") + r.Handle("/api/users", http.HandlerFunc(apiAllUsersHandler)).Methods("GET") + r.Handle("/api/users", http.HandlerFunc(apiCreateUsersHandler)).Methods("POST") + r.Handle("/api/users/{id}", http.HandlerFunc(apiUserHandler)).Methods("GET") + r.Handle("/api/users/{id}", http.HandlerFunc(apiUserUpdateHandler)).Methods("POST") + r.Handle("/api/users/{id}", http.HandlerFunc(apiUserDeleteHandler)).Methods("DELETE") // Generic API Routes - r.Handle("/api", http.HandlerFunc(ApiIndexHandler)) - r.Handle("/api/renew", http.HandlerFunc(ApiRenewHandler)) - r.Handle("/api/checkin/{api}", http.HandlerFunc(ApiCheckinHandler)) - r.Handle("/metrics", http.HandlerFunc(PrometheusHandler)) - r.NotFoundHandler = http.HandlerFunc(Error404Handler) - r.Handle("/tray", http.HandlerFunc(TrayHandler)) + r.Handle("/api", http.HandlerFunc(apiIndexHandler)) + r.Handle("/api/renew", http.HandlerFunc(apiRenewHandler)) + r.Handle("/api/checkin/{api}", http.HandlerFunc(apiCheckinHandler)) + r.Handle("/metrics", http.HandlerFunc(prometheusHandler)) + r.NotFoundHandler = http.HandlerFunc(error404Handler) + r.Handle("/tray", http.HandlerFunc(trayHandler)) return r } diff --git a/handlers/services.go b/handlers/services.go index 1a3dd363..165af12b 100644 --- a/handlers/services.go +++ b/handlers/services.go @@ -30,7 +30,7 @@ type Service struct { *types.Service } -func RenderServiceChartHandler(w http.ResponseWriter, r *http.Request) { +func renderServiceChartHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -39,22 +39,22 @@ func RenderServiceChartHandler(w http.ResponseWriter, r *http.Request) { service := core.SelectService(utils.StringInt(vars["id"])) w.Header().Set("Content-Type", "text/javascript") w.Header().Set("Cache-Control", "max-age=60") - ExecuteJSResponse(w, r, "charts.js", []*core.Service{service}) + executeJSResponse(w, r, "charts.js", []*core.Service{service}) } -func RenderServiceChartsHandler(w http.ResponseWriter, r *http.Request) { +func renderServiceChartsHandler(w http.ResponseWriter, r *http.Request) { services := core.CoreApp.Services w.Header().Set("Content-Type", "text/javascript") w.Header().Set("Cache-Control", "max-age=60") - ExecuteJSResponse(w, r, "charts.js", services) + executeJSResponse(w, r, "charts.js", services) } -func ServicesHandler(w http.ResponseWriter, r *http.Request) { +func servicesHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return } - ExecuteResponse(w, r, "services.html", core.CoreApp.Services, nil) + executeResponse(w, r, "services.html", core.CoreApp.Services, nil) } type serviceOrder struct { @@ -62,7 +62,7 @@ type serviceOrder struct { Order int `json:"order"` } -func ReorderServiceHandler(w http.ResponseWriter, r *http.Request) { +func reorderServiceHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -79,7 +79,7 @@ func ReorderServiceHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -func CreateServiceHandler(w http.ResponseWriter, r *http.Request) { +func createServiceHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -119,10 +119,10 @@ func CreateServiceHandler(w http.ResponseWriter, r *http.Request) { utils.Log(3, fmt.Sprintf("Error starting %v check routine. %v", service.Name, err)) } //notifiers.OnNewService(core.ReturnService(service.Service)) - ExecuteResponse(w, r, "services.html", core.CoreApp.Services, "/services") + executeResponse(w, r, "services.html", core.CoreApp.Services, "/services") } -func ServicesDeleteHandler(w http.ResponseWriter, r *http.Request) { +func servicesDeleteHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -134,20 +134,20 @@ func ServicesDeleteHandler(w http.ResponseWriter, r *http.Request) { return } service.Delete() - ExecuteResponse(w, r, "services.html", core.CoreApp.Services, "/services") + executeResponse(w, r, "services.html", core.CoreApp.Services, "/services") } -func ServicesViewHandler(w http.ResponseWriter, r *http.Request) { +func servicesViewHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) serv := core.SelectService(utils.StringInt(vars["id"])) if serv == nil { w.WriteHeader(http.StatusNotFound) return } - ExecuteResponse(w, r, "service.html", serv, nil) + executeResponse(w, r, "service.html", serv, nil) } -func ServicesUpdateHandler(w http.ResponseWriter, r *http.Request) { +func servicesUpdateHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -181,10 +181,10 @@ func ServicesUpdateHandler(w http.ResponseWriter, r *http.Request) { service.Update(true) service.Check(true) - ExecuteResponse(w, r, "service.html", service, "/services") + executeResponse(w, r, "service.html", service, "/services") } -func ServicesDeleteFailuresHandler(w http.ResponseWriter, r *http.Request) { +func servicesDeleteFailuresHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -192,10 +192,10 @@ func ServicesDeleteFailuresHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) service := core.SelectService(utils.StringInt(vars["id"])) service.DeleteFailures() - ExecuteResponse(w, r, "services.html", core.CoreApp.Services, "/services") + executeResponse(w, r, "services.html", core.CoreApp.Services, "/services") } -func CheckinCreateUpdateHandler(w http.ResponseWriter, r *http.Request) { +func checkinCreateUpdateHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -210,5 +210,5 @@ func CheckinCreateUpdateHandler(w http.ResponseWriter, r *http.Request) { Api: utils.NewSHA1Hash(18), } checkin.Create() - ExecuteResponse(w, r, "service.html", service, "/services") + executeResponse(w, r, "service.html", service, "/services") } diff --git a/handlers/settings.go b/handlers/settings.go index 0b502fbb..dce4c231 100644 --- a/handlers/settings.go +++ b/handlers/settings.go @@ -24,17 +24,18 @@ import ( "github.com/hunterlong/statup/utils" "net/http" "net/url" + "strconv" ) -func SettingsHandler(w http.ResponseWriter, r *http.Request) { +func settingsHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return } - ExecuteResponse(w, r, "settings.html", core.CoreApp, nil) + executeResponse(w, r, "settings.html", core.CoreApp, nil) } -func SaveSettingsHandler(w http.ResponseWriter, r *http.Request) { +func saveSettingsHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -61,13 +62,17 @@ func SaveSettingsHandler(w http.ResponseWriter, r *http.Request) { if domain != app.Domain { app.Domain = domain } + timezone := r.PostForm.Get("timezone") + timeFloat, _ := strconv.ParseFloat(timezone, 10) + app.Timezone = float32(timeFloat) + app.UseCdn = (r.PostForm.Get("enable_cdn") == "on") core.CoreApp, _ = core.UpdateCore(app) //notifiers.OnSettingsSaved(core.CoreApp.ToCore()) - ExecuteResponse(w, r, "settings.html", core.CoreApp, "/settings") + executeResponse(w, r, "settings.html", core.CoreApp, "/settings") } -func SaveSASSHandler(w http.ResponseWriter, r *http.Request) { +func saveSASSHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -81,10 +86,10 @@ func SaveSASSHandler(w http.ResponseWriter, r *http.Request) { source.SaveAsset([]byte(mobile), utils.Directory, "scss/mobile.scss") source.CompileSASS(utils.Directory) ResetRouter() - ExecuteResponse(w, r, "settings.html", core.CoreApp, "/settings") + executeResponse(w, r, "settings.html", core.CoreApp, "/settings") } -func SaveAssetsHandler(w http.ResponseWriter, r *http.Request) { +func saveAssetsHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -101,17 +106,17 @@ func SaveAssetsHandler(w http.ResponseWriter, r *http.Request) { utils.Log(2, "Default 'base.css' was insert because SASS did not work.") } ResetRouter() - ExecuteResponse(w, r, "settings.html", core.CoreApp, "/settings") + executeResponse(w, r, "settings.html", core.CoreApp, "/settings") } -func DeleteAssetsHandler(w http.ResponseWriter, r *http.Request) { +func deleteAssetsHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return } source.DeleteAllAssets(utils.Directory) ResetRouter() - ExecuteResponse(w, r, "settings.html", core.CoreApp, "/settings") + executeResponse(w, r, "settings.html", core.CoreApp, "/settings") } func parseId(r *http.Request) int64 { @@ -124,7 +129,7 @@ func parseForm(r *http.Request) url.Values { return r.PostForm } -func SaveNotificationHandler(w http.ResponseWriter, r *http.Request) { +func saveNotificationHandler(w http.ResponseWriter, r *http.Request) { var err error if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) @@ -147,7 +152,7 @@ func SaveNotificationHandler(w http.ResponseWriter, r *http.Request) { notifer, notif, err := notifier.SelectNotifier(method) if err != nil { utils.Log(3, fmt.Sprintf("issue saving notifier %v: %v", method, err)) - ExecuteResponse(w, r, "settings.html", core.CoreApp, "/settings") + executeResponse(w, r, "settings.html", core.CoreApp, "/settings") return } @@ -184,5 +189,5 @@ func SaveNotificationHandler(w http.ResponseWriter, r *http.Request) { utils.Log(3, fmt.Sprintf("issue updating notifier: %v", err)) } notifier.OnSave(notifer.Method) - ExecuteResponse(w, r, "settings.html", core.CoreApp, "/settings") + executeResponse(w, r, "settings.html", core.CoreApp, "/settings") } diff --git a/handlers/setup.go b/handlers/setup.go index 903c8b05..54365be8 100644 --- a/handlers/setup.go +++ b/handlers/setup.go @@ -25,7 +25,7 @@ import ( "time" ) -func SetupHandler(w http.ResponseWriter, r *http.Request) { +func setupHandler(w http.ResponseWriter, r *http.Request) { if core.CoreApp.Services != nil { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -51,10 +51,10 @@ func SetupHandler(w http.ResponseWriter, r *http.Request) { Password: "", } } - ExecuteResponse(w, r, "setup.html", data, nil) + executeResponse(w, r, "setup.html", data, nil) } -func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) { +func processSetupHandler(w http.ResponseWriter, r *http.Request) { var err error if core.CoreApp.Services != nil { http.Redirect(w, r, "/", http.StatusSeeOther) @@ -98,7 +98,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) { if err != nil { utils.Log(4, err) config.Error = err - SetupResponseError(w, r, config) + setupResponseError(w, r, config) return } @@ -106,7 +106,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) { if err != nil { utils.Log(3, err) config.Error = err - SetupResponseError(w, r, config) + setupResponseError(w, r, config) return } @@ -115,7 +115,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) { utils.Log(4, err) core.DeleteConfig() config.Error = err - SetupResponseError(w, r, config) + setupResponseError(w, r, config) return } @@ -126,7 +126,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) { if err != nil { utils.Log(4, err) config.Error = err - SetupResponseError(w, r, config) + setupResponseError(w, r, config) return } @@ -149,6 +149,6 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/", http.StatusSeeOther) } -func SetupResponseError(w http.ResponseWriter, r *http.Request, a interface{}) { - ExecuteResponse(w, r, "setup.html", a, nil) +func setupResponseError(w http.ResponseWriter, r *http.Request, a interface{}) { + executeResponse(w, r, "setup.html", a, nil) } diff --git a/handlers/users.go b/handlers/users.go index e00cfbfe..c885c30a 100644 --- a/handlers/users.go +++ b/handlers/users.go @@ -25,16 +25,16 @@ import ( "strconv" ) -func UsersHandler(w http.ResponseWriter, r *http.Request) { +func usersHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return } users, _ := core.SelectAllUsers() - ExecuteResponse(w, r, "users.html", users, nil) + executeResponse(w, r, "users.html", users, nil) } -func UsersEditHandler(w http.ResponseWriter, r *http.Request) { +func usersEditHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -42,10 +42,10 @@ func UsersEditHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, _ := strconv.Atoi(vars["id"]) user, _ := core.SelectUser(int64(id)) - ExecuteResponse(w, r, "user.html", user, nil) + executeResponse(w, r, "user.html", user, nil) } -func UpdateUserHandler(w http.ResponseWriter, r *http.Request) { +func updateUserHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -69,10 +69,10 @@ func UpdateUserHandler(w http.ResponseWriter, r *http.Request) { } user.Update() users, _ := core.SelectAllUsers() - ExecuteResponse(w, r, "users.html", users, "/users") + executeResponse(w, r, "users.html", users, "/users") } -func CreateUserHandler(w http.ResponseWriter, r *http.Request) { +func createUserHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -94,10 +94,10 @@ func CreateUserHandler(w http.ResponseWriter, r *http.Request) { utils.Log(3, err) } //notifiers.OnNewUser(user) - ExecuteResponse(w, r, "users.html", user, "/users") + executeResponse(w, r, "users.html", user, "/users") } -func UsersDeleteHandler(w http.ResponseWriter, r *http.Request) { +func usersDeleteHandler(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { http.Redirect(w, r, "/", http.StatusSeeOther) return diff --git a/notifiers/discord.go b/notifiers/discord.go index a0542efd..ce65d9e3 100644 --- a/notifiers/discord.go +++ b/notifiers/discord.go @@ -24,17 +24,12 @@ import ( "time" ) -const ( - DISCORD_METHOD = "discord" - DISCORD_TEST = `{"content": "This is a notification from Statup!"}` -) - type Discord struct { *notifier.Notification } var discorder = &Discord{¬ifier.Notification{ - Method: DISCORD_METHOD, + Method: "discord", Title: "Discord", Description: "Send notifications to your discord channel using discord webhooks. Insert your Discord channel webhook URL to receive notifications. Based on the Discord Webhook API.", Author: "Hunter Long", diff --git a/notifiers/discord_test.go b/notifiers/discord_test.go index 21d25b8e..1f5086a8 100644 --- a/notifiers/discord_test.go +++ b/notifiers/discord_test.go @@ -18,6 +18,7 @@ func init() { } func TestDiscordNotifier(t *testing.T) { + t.Parallel() if DISCORD_URL == "" { t.Log("Discord notifier testing skipped, missing DISCORD_URL environment variable") t.SkipNow() @@ -31,12 +32,10 @@ func TestDiscordNotifier(t *testing.T) { assert.Nil(t, err) assert.Equal(t, "Hunter Long", discorder.Author) assert.Equal(t, DISCORD_URL, discorder.Host) - assert.Equal(t, currentCount+1, CountNotifiers()) }) t.Run("Load Discord Notifier", func(t *testing.T) { - count := notifier.Load() - assert.Equal(t, currentCount+1, len(count)) + notifier.Load() }) t.Run("Discord Within Limits", func(t *testing.T) { diff --git a/notifiers/email_test.go b/notifiers/email_test.go index a13f0731..b630d95e 100644 --- a/notifiers/email_test.go +++ b/notifiers/email_test.go @@ -31,6 +31,7 @@ func init() { } func TestEmailNotifier(t *testing.T) { + t.Parallel() if EMAIL_HOST == "" || EMAIL_USER == "" || EMAIL_PASS == "" { t.Log("Email notifier testing skipped, missing EMAIL_ environment variables") t.SkipNow() @@ -62,12 +63,10 @@ func TestEmailNotifier(t *testing.T) { assert.Nil(t, err) assert.Equal(t, "Hunter Long", emailer.Author) assert.Equal(t, EMAIL_HOST, emailer.Host) - assert.Equal(t, currentCount+1, CountNotifiers()) }) t.Run("Emailer Load", func(t *testing.T) { - count := notifier.Load() - assert.Equal(t, currentCount+1, len(count)) + notifier.Load() }) t.Run("Email Within Limits", func(t *testing.T) { diff --git a/notifiers/slack_test.go b/notifiers/slack_test.go index fa2b8804..a6f684f7 100644 --- a/notifiers/slack_test.go +++ b/notifiers/slack_test.go @@ -23,6 +23,7 @@ func init() { } func TestSlackNotifier(t *testing.T) { + t.Parallel() if SLACK_URL == "" { t.Log("Slack notifier testing skipped, missing SLACK_URL environment variable") t.SkipNow() @@ -36,12 +37,10 @@ func TestSlackNotifier(t *testing.T) { assert.Nil(t, err) assert.Equal(t, "Hunter Long", slacker.Author) assert.Equal(t, SLACK_URL, slacker.Host) - assert.Equal(t, currentCount+1, CountNotifiers()) }) t.Run("Load Slack Notifier", func(t *testing.T) { - count := notifier.Load() - assert.Equal(t, currentCount+1, len(count)) + notifier.Load() }) t.Run("Slack parse message", func(t *testing.T) { diff --git a/notifiers/twilio.go b/notifiers/twilio.go index 676d0c59..19f87f91 100644 --- a/notifiers/twilio.go +++ b/notifiers/twilio.go @@ -29,30 +29,26 @@ import ( "time" ) -const ( - twilioMethod = "twilioNotifier" -) - type twilio struct { *notifier.Notification } var twilioNotifier = &twilio{¬ifier.Notification{ - Method: twilioMethod, - Title: "twilioNotifier", - Description: "Receive SMS text messages directly to your cellphone when a service is offline. You can use a twilioNotifier test account with limits. This notifier uses the twilioNotifier API.", + Method: "twilio", + Title: "Twilio", + Description: "Receive SMS text messages directly to your cellphone when a service is offline. You can use a Twilio test account with limits. This notifier uses the Twilio API.", Author: "Hunter Long", AuthorUrl: "https://github.com/hunterlong", Delay: time.Duration(10 * time.Second), Form: []notifier.NotificationForm{{ Type: "text", Title: "Account Sid", - Placeholder: "Insert your twilioNotifier Account Sid", + Placeholder: "Insert your Twilio Account Sid", DbField: "api_key", }, { Type: "text", Title: "Account Token", - Placeholder: "Insert your twilioNotifier Account Token", + Placeholder: "Insert your Twilio Account Token", DbField: "api_secret", }, { Type: "text", @@ -82,7 +78,7 @@ func (u *twilio) Select() *notifier.Notification { // Send will send a HTTP Post to the Twilio SMS API. It accepts type: string func (u *twilio) Send(msg interface{}) error { message := msg.(string) - twilioUrl := fmt.Sprintf("https://api.twilioNotifier.com/2010-04-01/Accounts/%v/Messages.json", u.GetValue("api_key")) + twilioUrl := fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%v/Messages.json", u.GetValue("api_key")) client := &http.Client{} v := url.Values{} v.Set("To", "+"+u.Var1) @@ -101,7 +97,7 @@ func (u *twilio) Send(msg interface{}) error { contents, _ := ioutil.ReadAll(res.Body) success, twilioRes := twilioSuccess(contents) if !success { - return errors.New(fmt.Sprintf("twilioNotifier didn't receive the expected status of 'enque' from API got: %v", twilioRes)) + return errors.New(fmt.Sprintf("Twilio didn't receive the expected status of 'enque' from API got: %v", twilioRes)) } return nil } diff --git a/notifiers/twilio_test.go b/notifiers/twilio_test.go index 9a13554b..3e0e313d 100644 --- a/notifiers/twilio_test.go +++ b/notifiers/twilio_test.go @@ -24,6 +24,7 @@ func init() { } func TestTwilioNotifier(t *testing.T) { + t.Parallel() if TWILIO_SID == "" || TWILIO_SECRET == "" || TWILIO_FROM == "" { t.Log("twilioNotifier notifier testing skipped, missing TWILIO_SID environment variable") t.SkipNow() @@ -37,12 +38,10 @@ func TestTwilioNotifier(t *testing.T) { assert.Nil(t, err) assert.Equal(t, "Hunter Long", twilioNotifier.Author) assert.Equal(t, TWILIO_SID, twilioNotifier.ApiKey) - assert.Equal(t, currentCount+1, CountNotifiers()) }) t.Run("Load twilioNotifier Notifier", func(t *testing.T) { - count := notifier.Load() - assert.Equal(t, currentCount+1, len(count)) + notifier.Load() }) t.Run("twilioNotifier Within Limits", func(t *testing.T) { diff --git a/source/tmpl/settings.html b/source/tmpl/settings.html index e88a8d36..dac4f87b 100644 --- a/source/tmpl/settings.html +++ b/source/tmpl/settings.html @@ -82,6 +82,43 @@ +
+ Current: {{.CurrentTime}} + +
+
diff --git a/types/failure.go b/types/failure.go index c94e38f5..57713984 100644 --- a/types/failure.go +++ b/types/failure.go @@ -4,6 +4,8 @@ import ( "time" ) +// Failure is a failed attempt to check a service. Any a service does not meet the expected requirements, +// a new Failure will be inserted into database. type Failure struct { Id int64 `gorm:"primary_key;column:id" json:"id"` Issue string `gorm:"column:issue" json:"issue"` diff --git a/types/service.go b/types/service.go index dd107055..8b5f761c 100644 --- a/types/service.go +++ b/types/service.go @@ -58,45 +58,6 @@ type ServiceInterface interface { Delete() error } -//type ServiceInterface interface { -// // Database functions -// Create() (int64, error) -// Update(bool) error -// Delete() error -// // Basic Method functions -// AvgTime() float64 -// OnlineSince(time.Time) float32 -// Online24() float32 -// SmallText() string -// GraphData() string -// AvgUptime(time.Time) string -// AvgUptime24() string -// ToJSON() string -// // Failure functions -// CreateFailure(*Failure) (int64, error) -// //LimitedFailures() []interface{} -// //AllFailures() []*Failure -// TotalFailuresSince(time.Time) (uint64, error) -// TotalFailures24() (uint64, error) -// TotalFailures() (uint64, error) -// DeleteFailures() -// // Hits functions (successful responses) -// CreateHit(*Hit) (int64, error) -// Hits() ([]*Hit, error) -// TotalHits() (uint64, error) -// TotalHitsSince(time.Time) (uint64, error) -// Sum() (float64, error) -// LimitedHits() ([]*Hit, error) -// SelectHitsGroupBy(string) ([]*Hit, error) -// // Go Routines -// CheckQueue(bool) -// Check(bool) -// //checkHttp(bool) *Service -// //checkTcp(bool) *Service -// // Checkin functions -// //AllCheckins() []*Checkin -//} - // Start will create a channel for the service checking go routine func (s *Service) Start() { s.Running = make(chan bool) diff --git a/utils/utils.go b/utils/utils.go index a03feab6..614808bf 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -17,6 +17,7 @@ package utils import ( "errors" + "fmt" "github.com/ararog/timeago" "io" "os" @@ -46,9 +47,25 @@ func StringInt(s string) int64 { return int64(num) } -// IntString converts a int to a string -func IntString(s int) string { - return strconv.Itoa(s) +// ToString converts a int to a string +func ToString(s interface{}) string { + switch v := s.(type) { + case int, int32, int64: + return fmt.Sprintf("%v", v) + case float32, float64: + return fmt.Sprintf("%v", v) + case []byte: + return string(v) + } + return "" +} + +func Timezoner(t time.Time, zone float32) time.Time { + zoneInt := float32(3600) * (zone + 1) + fmt.Println(int(zoneInt)) + loc := time.FixedZone("", int(zoneInt)) + timez := t.In(loc) + return timez } // dir returns the current working directory diff --git a/utils/utils_test.go b/utils/utils_test.go index 0b7bf05a..10c0d455 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -61,13 +61,27 @@ func TestLogHTTP(t *testing.T) { } func TestIntString(t *testing.T) { - assert.Equal(t, "1", IntString(1)) + assert.Equal(t, "1", ToString(1)) } func TestStringInt(t *testing.T) { assert.Equal(t, int64(1), StringInt("1")) } +func TestDbTime(t *testing.T) { + +} + +func TestTimezone(t *testing.T) { + zone := -5 + loc, _ := time.LoadLocation("America/Los_Angeles") + timestamp := time.Date(2018, 1, 1, 10, 0, 0, 0, loc).UTC() + correct := timestamp.Add(3 * time.Hour) + timezone := Timezoner(timestamp, zone) + assert.Equal(t, "2018-01-01 21:00:00 +0000 UTC", correct.String()) + assert.Equal(t, "2018-01-01 13:00:00 -0500 -0500", timezone.String()) +} + func TestTimestamp_Ago(t *testing.T) { now := Timestamp(time.Now()) assert.Equal(t, "Just now", now.Ago())