-
Notifications
You must be signed in to change notification settings - Fork 0
/
dashboard.go
executable file
·61 lines (53 loc) · 1.54 KB
/
dashboard.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
package handler
import (
"context"
"errors"
"net/http"
"time"
"github.com/greatfocus/gf-notify/repositories"
"github.com/greatfocus/gf-sframe/server"
)
// Dashboard struct
type Dashboard struct {
DashboardHandler func(http.ResponseWriter, *http.Request)
dashboardRepository *repositories.DashboardRepository
meta *server.Meta
}
// ServeHTTP checks if is valid method
func (hdl Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
hdl.getDashboard(w, r)
return
}
// catch all
// if no method is satisfied return an error
w.WriteHeader(http.StatusMethodNotAllowed)
w.Header().Add("Allow", "GET")
}
// Init method
func (hdl *Dashboard) Init(meta *server.Meta) {
hdl.dashboardRepository = &repositories.DashboardRepository{}
hdl.dashboardRepository.Init(meta.DB, meta.Cache)
hdl.meta = meta
}
// getDashboard method gets dashboard
func (hdl *Dashboard) getDashboard(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(hdl.meta.Timeout)*time.Second)
defer cancel()
year := r.FormValue("year")
month := r.FormValue("month")
if year != "" && month != "" {
dashboard, err := hdl.dashboardRepository.Get(ctx, year, month)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
hdl.meta.Error(w, r, err)
return
}
w.WriteHeader(http.StatusOK)
hdl.meta.Success(w, r, dashboard)
return
}
derr := errors.New("invalid payload request")
w.WriteHeader(http.StatusUnprocessableEntity)
hdl.meta.Error(w, r, derr)
}