Convers query results to CSV with format flag

This commit is contained in:
Dan Sosedoff 2014-10-10 18:56:02 -05:00
parent 2e766af361
commit 38cef071e8
2 changed files with 42 additions and 0 deletions

12
api.go
View File

@ -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)
} }

View File

@ -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()
}