terminal.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package middleware
  2. // Ported from Goji's middleware, source:
  3. // https://github.com/zenazn/goji/tree/master/web/middleware
  4. import (
  5. "fmt"
  6. "io"
  7. "os"
  8. )
  9. var (
  10. // Normal colors
  11. nBlack = []byte{'\033', '[', '3', '0', 'm'}
  12. nRed = []byte{'\033', '[', '3', '1', 'm'}
  13. nGreen = []byte{'\033', '[', '3', '2', 'm'}
  14. nYellow = []byte{'\033', '[', '3', '3', 'm'}
  15. nBlue = []byte{'\033', '[', '3', '4', 'm'}
  16. nMagenta = []byte{'\033', '[', '3', '5', 'm'}
  17. nCyan = []byte{'\033', '[', '3', '6', 'm'}
  18. nWhite = []byte{'\033', '[', '3', '7', 'm'}
  19. // Bright colors
  20. bBlack = []byte{'\033', '[', '3', '0', ';', '1', 'm'}
  21. bRed = []byte{'\033', '[', '3', '1', ';', '1', 'm'}
  22. bGreen = []byte{'\033', '[', '3', '2', ';', '1', 'm'}
  23. bYellow = []byte{'\033', '[', '3', '3', ';', '1', 'm'}
  24. bBlue = []byte{'\033', '[', '3', '4', ';', '1', 'm'}
  25. bMagenta = []byte{'\033', '[', '3', '5', ';', '1', 'm'}
  26. bCyan = []byte{'\033', '[', '3', '6', ';', '1', 'm'}
  27. bWhite = []byte{'\033', '[', '3', '7', ';', '1', 'm'}
  28. reset = []byte{'\033', '[', '0', 'm'}
  29. )
  30. var IsTTY bool
  31. func init() {
  32. // This is sort of cheating: if stdout is a character device, we assume
  33. // that means it's a TTY. Unfortunately, there are many non-TTY
  34. // character devices, but fortunately stdout is rarely set to any of
  35. // them.
  36. //
  37. // We could solve this properly by pulling in a dependency on
  38. // code.google.com/p/go.crypto/ssh/terminal, for instance, but as a
  39. // heuristic for whether to print in color or in black-and-white, I'd
  40. // really rather not.
  41. fi, err := os.Stdout.Stat()
  42. if err == nil {
  43. m := os.ModeDevice | os.ModeCharDevice
  44. IsTTY = fi.Mode()&m == m
  45. }
  46. }
  47. // colorWrite
  48. func cW(w io.Writer, useColor bool, color []byte, s string, args ...interface{}) {
  49. if IsTTY && useColor {
  50. w.Write(color)
  51. }
  52. fmt.Fprintf(w, s, args...)
  53. if IsTTY && useColor {
  54. w.Write(reset)
  55. }
  56. }