-
Notifications
You must be signed in to change notification settings - Fork 1
/
evolution.go
92 lines (74 loc) · 1.85 KB
/
evolution.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"bytes"
"context"
"encoding/csv"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/labstack/echo/v4"
)
type DolarEvolutionDay struct {
Date string `json:"date"`
Source string `json:"source"`
ValueSell Number `json:"value_sell"`
ValueBuy Number `json:"value_buy"`
}
func getDolarEvolutionData(days string, db *pgxpool.Pool) []DolarEvolutionDay {
limitStr := ""
var res []DolarEvolutionDay
if days != "" {
days_num, err := strconv.Atoi(days)
if err == nil && days_num < 10000 {
limitStr = "limit " + days
}
}
rows, err := db.Query(context.Background(), `
select
dttm, tipo, value_sell, value_buy
from
dolar_evolution
order by
dttm desc
`+limitStr)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var objAppend DolarEvolutionDay
var dateObj time.Time
if err := rows.Scan(&dateObj, &objAppend.Source, &objAppend.ValueSell, &objAppend.ValueBuy); err != nil {
log.Fatal(err)
}
objAppend.Date = fmt.Sprintf(dateObj.Format("2006-01-02"))
res = append(res, objAppend)
}
return res
}
func dolar_evolution_json(c echo.Context, db *pgxpool.Pool) error {
days := c.QueryParam("days")
res_data := getDolarEvolutionData(days, db)
return c.JSON(http.StatusOK, res_data)
}
func dolar_evolution_csv(c echo.Context, db *pgxpool.Pool) error {
days := c.QueryParam("days")
res_data := getDolarEvolutionData(days, db)
csv_data := [][]string{
{"day", "type", "value_buy", "value_sell"},
}
for _, d := range res_data {
tmp := []string{d.Date, d.Source, fmt.Sprintf("%.2f", d.ValueBuy), fmt.Sprintf("%.2f", d.ValueSell)}
csv_data = append(csv_data, tmp)
}
b := new(bytes.Buffer)
w := csv.NewWriter(b)
w.WriteAll(csv_data)
if err := w.Error(); err != nil {
log.Fatal(err)
}
return c.Blob(http.StatusOK, "text/csv", b.Bytes())
}