示例#1
0
func dataHandler(w http.ResponseWriter, r *http.Request, db *data.Database) {
	var queries []map[string]string
	err := json.Unmarshal([]byte(r.FormValue("query")), &queries)
	if err != nil {
		jww.ERROR.Println(err)
		return
	}
	//channel := r.FormValue("channel")

	t, interval := computeTime(r.FormValue("time"))

	var result struct {
		Data      [][]interface{}
		Errorbars [][]interface{}
		Label     []string
	}
	result.Data = make([][]interface{}, len(queries))
	result.Errorbars = make([][]interface{}, len(queries))
	result.Label = make([]string, len(queries))

	rxp := regexp.MustCompile(`\[([^]]*)\]`)
	for index, querymap := range queries {
		id := "%"
		if _, ok := querymap["id"]; ok {
			id = querymap["id"]
		}
		datatype := "%"
		if _, ok := querymap["type"]; ok {
			datatype = querymap["type"]
		}
		if _, ok := querymap["label"]; ok {
			result.Label[index] = querymap["label"]
		} else {
			result.Label[index] = "Unknown"
		}

		key := rxp.ReplaceAllString(datatype, "")
		var rows <-chan data.Row
		if interval > 1 {
			rows = db.QueryRowsInterval(t, key, id, interval)
		} else {
			rows = db.QueryRows(t, key, id)
		}

		col := rxp.FindStringSubmatch(datatype)

		unitmap := viper.GetStringMapString("units")
		for row := range rows {
			_, off := time.Unix(row.Timestamp, 0).Zone()
			t := (time.Unix(row.Timestamp, 0).Unix() + int64(off)) * 1000
			sub := make([]interface{}, 2)
			sub[0] = t
			var value float64
			if len(col) > 1 {
				switch col[1] {
				case "min":
					value = row.Min
				case "max":
					value = row.Max
				case "avg":
					value = row.Avg
				default:
					value = row.Avg
				}
			} else {
				value = row.Avg
			}
			sub[1] = convertUnit(unitmap, r.FormValue("type"), value)
			result.Data[index] = append(result.Data[index], sub)

			sub = make([]interface{}, 3)
			sub[0] = t
			sub[1] = convertUnit(unitmap, r.FormValue("type"), row.Min)
			sub[2] = convertUnit(unitmap, r.FormValue("type"), row.Max)
			result.Errorbars[index] = append(result.Errorbars[index], sub)
		}
		index++
	}
	json.NewEncoder(w).Encode(result)
}