123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- package model
- import (
- "encoding/json"
- iclient "github.com/influxdata/influxdb/client/v2"
- "github.com/jaryhe/gopkgs/influxdb"
- "time"
- )
- func QueryInfluxdb(sql string, db string, result interface{}) ([]map[string]interface{}, error) {
- qt := iclient.Query{
- Database:db,
- Command:sql,
- }
- r, err := influxdb.InfluxCli.Query(qt)
- if err != nil {
- return nil, err
- }
- if r == nil {
- return nil, nil
- }
- if len(r.Results) == 0 {
- return nil, nil
- }
- if len(r.Results[0].Series) == 0 {
- return nil, nil
- }
- colNames := r.Results[0].Series[0].Columns
- var marray = make([]map[string]interface{}, len(r.Results[0].Series[0].Values))
- for i, row := range r.Results[0].Series[0].Values {
- item := map[string]interface{}{}
- for j , v := range row {
- if colNames[j] == "time" {
- t,_ := time.Parse(time.RFC3339, v.(string))
- v = t.Format("2006-01-02 15:04:05")
- }
- item[colNames[j]] = v
- }
- marray[i] = item
- }
- if result != nil {
- bytes, _ := json.Marshal(marray)
- err = json.Unmarshal(bytes, result)
- if err != nil {
- return nil, err
- }
- }
- return marray, nil
- }
|