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