|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/fatih/color" |
| 9 | +) |
| 10 | + |
| 11 | +// runLogUI prints the startup banner then one line per incoming Event. |
| 12 | +// Returns after events channel is closed. Prints a summary on exit. |
| 13 | +func runLogUI(w io.Writer, listenAddr, upstream string, events <-chan Event) { |
| 14 | + color.NoColor = !isTerminal(w) |
| 15 | + |
| 16 | + fmt.Fprintln(w) |
| 17 | + fmt.Fprintf(w, " %s httpsdev v%s\n\n", color.CyanString("▲"), Version) |
| 18 | + fmt.Fprintf(w, " %s Local: %s\n", color.GreenString("➜"), color.New(color.Bold).Sprintf("https://%s", listenAddr)) |
| 19 | + fmt.Fprintf(w, " %s Upstream: %s\n", color.GreenString("➜"), upstream) |
| 20 | + fmt.Fprintf(w, " %s Cert: mkcert · valid 30 days\n\n", color.GreenString("➜")) |
| 21 | + fmt.Fprintf(w, " press Ctrl+C to quit\n\n") |
| 22 | + |
| 23 | + var total, errors int |
| 24 | + var totalDur time.Duration |
| 25 | + start := time.Now() |
| 26 | + |
| 27 | + for ev := range events { |
| 28 | + total++ |
| 29 | + totalDur += ev.Duration |
| 30 | + if ev.Status >= 400 { |
| 31 | + errors++ |
| 32 | + } |
| 33 | + fmt.Fprintln(w, formatEvent(ev)) |
| 34 | + } |
| 35 | + |
| 36 | + if total == 0 { |
| 37 | + return |
| 38 | + } |
| 39 | + avg := totalDur / time.Duration(total) |
| 40 | + fmt.Fprintf(w, "\nserved %d requests · %d errors · avg %s · uptime %s\n", |
| 41 | + total, errors, avg.Round(time.Millisecond), time.Since(start).Round(time.Second)) |
| 42 | +} |
| 43 | + |
| 44 | +func formatEvent(ev Event) string { |
| 45 | + statusColor := color.New(color.FgGreen) |
| 46 | + switch { |
| 47 | + case ev.Status >= 500: |
| 48 | + statusColor = color.New(color.FgRed, color.Bold) |
| 49 | + case ev.Status >= 400: |
| 50 | + statusColor = color.New(color.FgRed) |
| 51 | + case ev.Status >= 300: |
| 52 | + statusColor = color.New(color.FgYellow) |
| 53 | + } |
| 54 | + return fmt.Sprintf("%-6s %-30s %s %s", |
| 55 | + color.CyanString("%s", ev.Method), |
| 56 | + ev.Path, |
| 57 | + statusColor.Sprintf("%d", ev.Status), |
| 58 | + ev.Duration.Round(time.Millisecond), |
| 59 | + ) |
| 60 | +} |
0 commit comments