// Handler of /api/2/pings/{origin}/{time} GET requests to retrieve the average // `transfer_time_ms` for a specific `origin`, aggregated by hours. The first // date is {time + 1 day} if way is set to "next" or {time - 1 day} if way is // set to "prev". func HandlerGetAvgPerHourDayShift(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) origin := vars["origin"] start, err := time.Parse("2006-01-02 15:04:05 +0000 UTC", vars["time"]) way := vars["way"] avgCollection := utils_json.NewAvgCollection(0) if err == nil { if way == "prev" { start = start.AddDate(0, 0, -1) avgCollection = connector.GetAverages(origin, start, time.Hour, 24) } else if way == "next" { start = start.AddDate(0, 0, +1) avgCollection = connector.GetAverages(origin, start, time.Hour, 24) } } utils_json.WriteAverages(w, avgCollection) }
func (connector *InfluxConnector) GetAverages( origin string, start time.Time, step time.Duration, count int) *utils_json.AvgCollection { avgCollection := utils_json.NewAvgCollection(count) startUnix := start.Unix() * 1000000000 stepUnix := int64(step.Seconds()) * 1000000000 for i := 0; i < count; i++ { query := fmt.Sprintf( "SELECT MEAN(transfer_time_ms) FROM ping WHERE origin = '%s' AND time > %d AND time < %d", origin, startUnix, startUnix+stepUnix, ) res, err := connector.query(query) if err != nil || len(res) == 0 { log.Println("Cannot query an average transfer time from InfluxDB.") } avgCollection.Averages[i] = 0 avgCollection.Times[i] = start.String() if len(res[0].Series) != 0 { if meanItf := res[0].Series[0].Values[0][1]; meanItf != nil { if f, err := meanItf.(json.Number).Float64(); err == nil { avgCollection.Averages[i] = f } } } start = start.Add(step) startUnix = startUnix + stepUnix } return avgCollection }