-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
373 lines (320 loc) · 9.25 KB
/
main.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"golang.org/x/net/html"
)
// HTTP client configuration
var client = &http.Client{Timeout: 10 * time.Second}
// Lip Gloss styles for JSON components and response display
var (
keyStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
stringStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("34"))
numberStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("178"))
boolStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("207"))
nullStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
respStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("205")).
Background(lipgloss.Color("236")).
Padding(1).
Margin(1).
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("63"))
)
const indentation = " "
type component int
const (
textInputFocus component = iota
methodListFocus
)
// Model definition and initialization
type model struct {
text string
urlInput textinput.Model
methodInput textinput.Model
focusedComponent component
quitting bool
}
func initialModel() model {
const defaultWidth = 40
url := textinput.New()
url.Placeholder = "Enter a valid URL"
url.Focus()
url.CharLimit = 256
url.Width = defaultWidth
method := textinput.New()
method.Placeholder = "HTTP Method"
method.CharLimit = 6
return model{text: "", urlInput: url, methodInput: method, focusedComponent: textInputFocus}
}
// Bubble Tea program functions
func (m model) Init() tea.Cmd {
return nil
}
var httpMethods = map[string]bool{
"GET": true,
"POST": true,
"PUT": true,
"DELETE": true,
"PATCH": true,
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
m.quitting = true
return m, tea.Quit
case "enter":
// Validate URL
input := m.urlInput.Value()
if !isValidURL(input) {
m.text = `{ "error": "invalid URL, please try again" }`
return m, nil
}
// Validate HTTP Method
method := strings.ToUpper(m.methodInput.Value())
if !httpMethods[method] {
m.text = `{ "error": "invalid HTTP method, please enter GET, POST, PUT, DELETE, or PATCH" }`
return m, nil
}
// Fetch and format data with the validated method
data, err := FetchData(input, method)
if err != nil {
m.text = data
} else {
m.text = data
}
return m, nil
case "down", "j":
if m.focusedComponent == textInputFocus {
m.focusedComponent = methodListFocus
m.urlInput.Blur()
m.methodInput.Focus()
}
return m, nil
case "up", "k":
if m.focusedComponent == methodListFocus {
m.focusedComponent = textInputFocus
m.methodInput.Blur()
m.urlInput.Focus()
}
return m, nil
case "tab":
// Toggle focus between urlInput and methodInput on Tab key press
if m.focusedComponent == methodListFocus {
m.focusedComponent = textInputFocus
m.methodInput.Blur()
m.urlInput.Focus()
} else {
m.focusedComponent = methodListFocus
m.urlInput.Blur()
m.methodInput.Focus()
}
return m, nil
}
}
var cmd tea.Cmd
// Update the input component based on which one is focused
if m.focusedComponent == textInputFocus {
m.urlInput, cmd = m.urlInput.Update(msg)
} else {
m.methodInput, cmd = m.methodInput.Update(msg)
}
return m, cmd
}
func (m model) View() string {
if m.quitting {
return "Thanks for using go-forth!\n"
}
content := respStyle.Render(m.text)
return fmt.Sprintf(
"\nPlease enter a URL for a GET request:\n\n%s\n\n%s\n\n%s\n%s\n",
m.urlInput.View(),
m.methodInput.View(),
content,
"Press ctrl+c to exit",
)
}
func FetchData(url, method string) (string, error) {
// Create a new request with the selected method
req, err := http.NewRequest(method, url, nil)
if err != nil {
return formatJSONError("failed to create the request", err.Error()), nil
}
// Execute the request
resp, err := client.Do(req)
if err != nil {
return formatJSONError("failed to make the request", err.Error()), nil
}
defer resp.Body.Close()
// Check if the response status code is not 200 OK
if resp.StatusCode != http.StatusOK {
return formatJSONError("received non-200 response code", fmt.Sprintf("%d", resp.StatusCode)), nil
}
// Read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return formatJSONError("failed to read the response body", err.Error()), nil
}
// Determine response format based on content type
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") && isJSON(body) {
// Attempt to pretty-print JSON
prettyJSON, err := prettyPrintJSON(string(body))
if err != nil {
return formatJSONError("error formatting JSON", err.Error()), nil
}
return prettyJSON, nil
}
// If not JSON, return as plain text with styling
return prettyPrintText(string(body)), nil
}
// Helper functions for data validation and formatting
func isValidURL(input string) bool {
parsedURL, err := url.ParseRequestURI(input)
return err == nil && parsedURL.Scheme != "" && parsedURL.Host != ""
}
func isJSON(data []byte) bool {
var js json.RawMessage
return json.Unmarshal(data, &js) == nil
}
func formatJSONError(message, details string) string {
return fmt.Sprintf(`{ "error": "%s", "details": "%s" }`, message, details)
}
func truncateString(str string, length int) string {
if len(str) <= length {
return str
}
return str[:length] + "..."
}
func formatHTMLText(data string) (string, error) {
// Parse the HTML
node, err := html.Parse(strings.NewReader(data))
if err != nil {
return "", err
}
// Use a buffer to capture formatted output
var buf bytes.Buffer
formatNode(&buf, node, 0)
return buf.String(), nil
}
func formatNode(buf *bytes.Buffer, n *html.Node, level int) {
// Skip the root node and <head> element for formatting purposes
if n.Type == html.DocumentNode || (n.Type == html.ElementNode && n.Data == "head") {
for c := n.FirstChild; c != nil; c = c.NextSibling {
formatNode(buf, c, level)
}
return
}
// Check if the node has only one child and that child is a text node
if n.Type == html.ElementNode && n.FirstChild != nil && n.FirstChild == n.LastChild && n.FirstChild.Type == html.TextNode {
// Inline text content within tags
indent(buf, level)
buf.WriteString("<" + n.Data + ">")
buf.WriteString(strings.TrimSpace(n.FirstChild.Data)) // Inline text
buf.WriteString("</" + n.Data + ">\n")
return
}
// Add opening tag with indentation
if n.Type == html.ElementNode {
indent(buf, level)
buf.WriteString("<" + n.Data + ">\n")
}
// Process child nodes
for c := n.FirstChild; c != nil; c = c.NextSibling {
formatNode(buf, c, level+1)
}
// Add closing tag for element nodes
if n.Type == html.ElementNode {
indent(buf, level)
buf.WriteString("</" + n.Data + ">\n")
} else if n.Type == html.TextNode {
// Add text content with indentation for multi-line text
text := strings.TrimSpace(n.Data)
if text != "" {
indent(buf, level)
buf.WriteString(text + "\n")
}
}
}
func indent(buf *bytes.Buffer, level int) {
buf.WriteString(strings.Repeat(" ", level))
}
func prettyPrintText(data string) string {
// Apply indentation using formatHTMLText, then style with lipgloss
formattedText, err := formatHTMLText(data)
if err != nil {
return formatJSONError("error formatting text", err.Error())
}
return lipgloss.NewStyle().
Foreground(lipgloss.Color("250")).
Background(lipgloss.Color("235")).
Padding(1).
Margin(1).
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("63")).
Render(truncateString(formattedText, 2000))
}
func prettyPrintJSON(data string) (string, error) {
if os.Getenv("TEST_MODE") == "true" {
// Skip pretty-printing during tests
return data, nil
}
var jsonData interface{}
if err := json.Unmarshal([]byte(data), &jsonData); err != nil {
return "", fmt.Errorf(`{ "error": "invalid JSON format", "details": "%v" }`, err)
}
return renderJSON(jsonData, 0), nil
}
func renderJSON(data interface{}, level int) string {
var buf bytes.Buffer
indent := strings.Repeat(indentation, level)
switch v := data.(type) {
case map[string]interface{}:
buf.WriteString("{\n")
for key, value := range v {
buf.WriteString(indent + indentation)
buf.WriteString(keyStyle.Render(fmt.Sprintf(`"%s"`, key)) + ": ")
buf.WriteString(renderJSON(value, level+1))
buf.WriteString(",\n")
}
buf.Truncate(buf.Len() - 2)
buf.WriteString("\n" + indent + "}")
case []interface{}:
buf.WriteString("[\n")
for _, item := range v {
buf.WriteString(indent + indentation)
buf.WriteString(renderJSON(item, level+1))
buf.WriteString(",\n")
}
buf.Truncate(buf.Len() - 2)
buf.WriteString("\n" + indent + "]")
case string:
buf.WriteString(stringStyle.Render(fmt.Sprintf(`"%s"`, v)))
case float64:
buf.WriteString(numberStyle.Render(fmt.Sprintf("%v", v)))
case bool:
buf.WriteString(boolStyle.Render(fmt.Sprintf("%v", v)))
case nil:
buf.WriteString(nullStyle.Render("null"))
}
return buf.String()
}
func main() {
p := tea.NewProgram(initialModel())
_, err := p.Run()
if err != nil {
fmt.Printf("Error running program: %v\n", err)
}
}