-
Notifications
You must be signed in to change notification settings - Fork 2
/
web.go
73 lines (62 loc) · 1.59 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 (
_ "embed"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
)
//go:embed pages/index.html
var IndexPage string
func RunPage(address string) {
http.HandleFunc("/datatransfers", func(w http.ResponseWriter, r *http.Request) {
billdate := r.URL.Query().Get("date")
if billdate == "" {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", errors.New("date parameter cannot be empty"))
return
}
start, end, err := GetDates(billdate)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
report, regionalreport, err := GenerateData(start, end, "MONTHLY")
if err != nil {
log.Printf("error: %s, start: %s, end: %s", err, start, end)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
data := struct {
Costs []UsageItem
Regions []RegionalUsage
Groups []string
}{
Costs: report,
Regions: regionalreport,
Groups: regions.GroupByRegion(),
}
rspdata, err := json.Marshal(data)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "%s", rspdata)
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", IndexPage)
})
err := http.ListenAndServe(address, nil)
if err != nil {
log.Fatal(err)
}
}
func GetDates(billdate string) (startdate, enddate string, err error) {
start, err := time.Parse("2006|January", billdate)
if err != nil {
return startdate, enddate, err
}
end := start.AddDate(0, 1, -1)
return start.Format("2006-01-02"), end.Format("2006-01-02"), nil
}