Add ability to export table to JSON and XML

This commit is contained in:
Dan Sosedoff
2016-01-04 18:03:53 -06:00
parent bc1f876fb5
commit 73a97893e9
6 changed files with 74 additions and 36 deletions

View File

@@ -196,20 +196,27 @@ func HandleQuery(query string, c *gin.Context) {
return
}
q := c.Request.URL.Query()
format := getQueryParam(c, "format")
filename := getQueryParam(c, "filename")
if len(q["format"]) > 0 && q["format"][0] == "csv" {
filename := fmt.Sprintf("pgweb-%v.csv", time.Now().Unix())
if len(q["filename"]) > 0 && q["filename"][0] != "" {
filename = q["filename"][0]
}
c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
c.Data(200, "text/csv", result.CSV())
return
if filename == "" {
filename = fmt.Sprintf("pgweb-%v.%v", time.Now().Unix(), format)
}
c.JSON(200, result)
if format != "" {
c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
}
switch format {
case "csv":
c.Data(200, "text/csv", result.CSV())
case "json":
c.Data(200, "applicaiton/json", result.JSON())
case "xml":
c.XML(200, result)
default:
c.JSON(200, result)
}
}
func GetBookmarks(c *gin.Context) {

View File

@@ -22,6 +22,17 @@ type Error struct {
Message string `json:"error"`
}
func getQueryParam(c *gin.Context, name string) string {
result := ""
q := c.Request.URL.Query()
if len(q[name]) > 0 {
result = q[name][0]
}
return result
}
func assetContentType(name string) string {
ext := filepath.Ext(name)
result := mime.TypeByExtension(ext)

View File

@@ -3,6 +3,7 @@ package client
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"reflect"
@@ -250,6 +251,21 @@ func (res *Result) CSV() []byte {
return buff.Bytes()
}
func (res *Result) JSON() []byte {
records := []map[string]interface{}{}
for _, row := range res.Rows {
record := map[string]interface{}{}
for i, col := range res.Columns {
record[col] = row[i]
}
records = append(records, record)
}
data, _ := json.Marshal(records)
return data
}
// Close database connection
func (client *Client) Close() error {
if client.db != nil {

File diff suppressed because one or more lines are too long