Convers query results to CSV with format flag
This commit is contained in:
parent
2e766af361
commit
38cef071e8
12
api.go
12
api.go
@ -68,5 +68,17 @@ func API_HandleQuery(query string, c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
q := c.Request.URL.Query()
|
||||||
|
|
||||||
|
format := q["format"][0]
|
||||||
|
if format == "" {
|
||||||
|
format = "json"
|
||||||
|
}
|
||||||
|
|
||||||
|
if format == "csv" {
|
||||||
|
c.String(200, result.CSV())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(200, result)
|
c.JSON(200, result)
|
||||||
}
|
}
|
||||||
|
30
client.go
30
client.go
@ -1,6 +1,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/csv"
|
||||||
|
"fmt"
|
||||||
"github.com/jmoiron/sqlx"
|
"github.com/jmoiron/sqlx"
|
||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
@ -107,3 +110,30 @@ func (res *Result) Format() []map[string]interface{} {
|
|||||||
|
|
||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (res *Result) CSV() string {
|
||||||
|
buff := &bytes.Buffer{}
|
||||||
|
writer := csv.NewWriter(buff)
|
||||||
|
|
||||||
|
for _, row := range res.Rows {
|
||||||
|
record := make([]string, len(res.Columns))
|
||||||
|
|
||||||
|
for i, item := range row {
|
||||||
|
if item != nil {
|
||||||
|
record[i] = fmt.Sprintf("%v", item)
|
||||||
|
} else {
|
||||||
|
record[i] = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err := writer.Write(record)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.Flush()
|
||||||
|
return buff.String()
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user