-
Notifications
You must be signed in to change notification settings - Fork 0
/
chart.go
279 lines (243 loc) Β· 6.63 KB
/
chart.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package gobarchar
import (
"fmt"
"html"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"golang.org/x/exp/slices"
)
var htmlFirstHalf string = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<title>GoBarChar</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
line-height: 1.33;
margin: 0 auto;
max-width: 650px;
padding: 1rem;
}
pre {
overflow: auto;
user-select: all;
}
a {
word-break: break-all;
}
h1 > a, h1 > a:visited {
color: black;
}
</style>
</head>
<body>
<h1><a href="/">GoBarChar</a></h1>
<p><strong>The charting solution that might not suit you π</strong></p>
<hr />
<p>What is this? This is a small <a href="https://github.com/usrme/gobarchar">project</a> to generate ASCII bar charts using just query parameters.</p>
<br/>
`
var htmlSecondHalf string = `<hr>
<footer>
<small>Hosted on <a href="https://fly.io">Fly</a>.</small>
</footer>
</body>
</html>`
type entry struct {
Label string
Value float64
}
// Create custom type that implements 'sort.Interface' for easier sorting
type chartData []entry
func (a chartData) Len() int { return len(a) }
func (a chartData) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a chartData) Less(i, j int) bool { return a[i].Value < a[j].Value }
func PresentBarChart(examples string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Check if there are any query parameters; if not, add random key-value pairs
if len(r.URL.Query()) == 0 {
encodeRandomQuery(r)
}
chart := createBarChart(r)
// Skip all templating if user is requesting through 'curl' or 'wget'
agent := r.UserAgent()
if strings.HasPrefix(agent, "curl") || strings.HasPrefix(agent, "Wget") {
w.Write([]byte(chart))
return
}
chartUrl := r.URL.String()
html := fmt.Sprintf(
"%s<pre>%s</pre><br/><hr><p>Link used to generate the current chart: <a href='%s'>%s</a></p>%s%s",
htmlFirstHalf, chart, chartUrl, chartUrl, examples, htmlSecondHalf,
)
w.Write([]byte(html))
}
}
func encodeRandomQuery(r *http.Request) {
params := r.URL.Query()
for i := 0; i < 6; i++ {
var month string
for {
month = randomMonth()
if !params.Has(month) {
break
}
}
value := rand.Intn(101)
params.Add(month, strconv.Itoa(value))
}
r.URL.RawQuery = params.Encode()
}
func randomMonth() string {
months := []string{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
}
return months[rand.Intn(len(months))]
}
func createBarChart(r *http.Request) string {
// Use custom type to make sorting easier
entries := make([]entry, 0)
maxValue, total := 0.0, 0.0
// Use 'RawQuery' instead of something like 'Query()' or other automatic
// methods to parse query parameters as those get turned into maps that
// then lose their order of appearance in the original query.
//
// The order make intuitive sense when presenting, otherwise every request
// with the same data shows the results with a slightly different order if
// the 'sort' query parameter isn't given.
raw := r.URL.RawQuery
orderedParams := strings.Split(raw, "&")
addSpaces := slices.Contains(orderedParams, "spaces=yes")
var title string
for _, pair := range orderedParams {
kv := strings.Split(pair, "=")
key := kv[0]
// Don't parse certain query parameters as they are not part of the data
switch key {
case "sort", "spaces":
continue
case "title":
title = strings.Replace(kv[1], "%20", " ", -1)
continue
}
count, err := strconv.ParseFloat(kv[1], 64)
if err == nil {
if addSpaces {
key = strings.Replace(key, "%20", " ", -1)
}
entries = append(entries, entry{Label: key, Value: float64(count)})
if count > maxValue {
maxValue = count
}
total += count
}
}
// Only remove the 'sort' query parameter if it was found.
sortOrder := r.URL.Query().Get("sort")
if sortOrder == "asc" {
sort.Sort(chartData(entries))
} else if sortOrder == "desc" {
sort.Sort(sort.Reverse(chartData(entries)))
}
avg := total / float64(len(entries))
entries = append(entries, entry{Label: "Avg.", Value: avg})
orderedParams = append(orderedParams, fmt.Sprintf("%s=%.2f", "Avg.", avg))
entries = append(entries, entry{Label: "Total", Value: total})
orderedParams = append(orderedParams, fmt.Sprintf("%s=%.2f", "Total", total))
increment := maxValue / 25.0
// Find the longest label to determine padding later on
longestLabelLength := 0
for _, entry := range entries {
if len(entry.Label) > longestLabelLength {
longestLabelLength = len(entry.Label)
}
}
longestValueLength := 0
for _, entry := range entries {
valueStr := formatValue(entry.Value)
if len(valueStr) > longestValueLength {
longestValueLength = len(valueStr)
}
}
var chartContent strings.Builder
if title != "" {
chartContent.WriteString(title + "\n\n")
}
maximumBarChunk := 0
for i := range entries {
// Skip parsing the total for now to not interfere with calculating
// the maximum number of bar chunks for all of the labels
if entries[i].Label == "Total" {
continue
}
barChunks := int(entries[i].Value * 8 / increment)
remainder := barChunks % 8
barChunks /= 8
if barChunks > maximumBarChunk {
maximumBarChunk = barChunks
}
bar := calculateBars(barChunks, remainder)
valueStr := formatValue(entries[i].Value)
chartContent.WriteString(
fmt.Sprintf(
"%s %s %s\n",
padRight(entries[i].Label, longestLabelLength), padLeft(valueStr, longestValueLength), bar,
),
)
}
bar := calculateBars(maximumBarChunk, 0)
totalStr := formatValue(total)
chartContent.WriteString(fmt.Sprintf("%s %s %s\n", padRight("Total", longestLabelLength), padLeft(totalStr, longestValueLength), bar))
return html.UnescapeString(chartContent.String())
}
func formatValue(value float64) string {
if value == float64(int(value)) {
return fmt.Sprintf("%4d", int(value))
}
return fmt.Sprintf("%6.2f", value)
}
func calculateBars(count, remainder int) string {
// First draw the full width chunks
bar := strings.Repeat("β", count)
// Then add the fractional part
if remainder > 0 {
bar += string(rune('β' + (8 - remainder)))
}
// If the bar is empty (i.e. a value of 0 was given), add a left one-eighth block
if bar == "" {
bar = "β"
}
return bar
}
func padRight(str string, length int) string {
if len(str) >= length {
return str
}
return str + strings.Repeat(" ", length-len(str))
}
func padLeft(str string, length int) string {
if len(str) >= length {
return str
}
return strings.Repeat(" ", length-len(str)) + str
}