package services import "time" type SensorValuesService struct { ctx *Context } type sensorValue struct { Timestamp int64 `json:"timestamp"` Value float64 `json:"value"` } func (s *SensorValuesService) Push(sensor string, value float64) (int64, error) { res, err := s.ctx.DB.Exec("INSERT INTO sensor_values (timestamp, sensor, value) VALUES (?, ?, ?)", time.Now().Unix(), sensor, value) if err != nil { return 0, err } return res.LastInsertId() } func (s *SensorValuesService) GetList(sensor string, from int64, to int64) ([]sensorValue, error) { var value float64 var timestamp int64 values := make([]sensorValue, 0) rows, err := s.ctx.DB.Query("SELECT timestamp, value FROM sensor_values WHERE sensor = ? AND timestamp > ? AND timestamp < ? ORDER BY timestamp ASC", sensor, from, to) if err != nil { return nil, err } defer rows.Close() for rows.Next() { err := rows.Scan(×tamp, &value) if err != nil { return nil, err } values = append(values, sensorValue{Timestamp: timestamp, Value: value}) } err = rows.Err() if err != nil { return nil, err } return values, nil } func (s *SensorValuesService) GetLatest(sensor string, to int64) (*sensorValue, error) { var value = sensorValue{} row := s.ctx.DB.QueryRow("SELECT timestamp, value FROM sensor_values WHERE sensor = ? timestamp < ? ORDER BY timestamp DESC LIMIT 1", sensor, to) err := row.Scan(&value.Timestamp, &value.Value) if err != nil { return nil, err } return &value, nil }