I am using the tabwriter and I cannot get it to work with colors. I am using the "github.com/fatih/color" package.
Basically the problem is that I need to call tabwriter's w.Flush()
in order to get the colors to render... I cannot switch colors if I have not called a flush.
Calling Flush in turn screws with the tabwriter formatting.
Any ideas on how to combine the two?
package main
import "fmt"
import "text/tabwriter"
import "os"
import "github.com/fatih/color"
func main() {
w := new(tabwriter.Writer)
w.Init(os.Stderr, 0, 8, 0, '\t', 0)
color.Set(color.FgGreen)
fmt.Fprintln(w, "ID\tNAME\tSIZE\tFIELD1\tSTATUS\tSTATE")
// ------> Calling w.Flush() here cases problems.
color.Set(color.FgYellow)
fmt.Fprintln(w, "8617833164795356724\tfoo1\t1.1 Gb\t3\tsome_status\tsome_state")
fmt.Fprintln(w)
w.Flush()
}
Despite what the accepted answer says, it is possible, you just have to be very careful about field length.
Wrap each "field" (i.e. a specific row and column) with a color+reset code. If all codes are of the same string length, tabwriter
will give you a good result.
I have a crude demonstration here: https://play.golang.org/p/r6GNeV1gbH
I didn't do so in my demo, but you should also add the background codes as well (you can simply add them together as in RedText + YellowBackground
), providing a default background. In this way, everything will be of equal length and you'll have background support as well.
Please note that I am a beginner Go programmer. I don't claim that my code is any good.
You can't.
Use the color.Color.SprintFunc()
method to get a function and wrap your strigns using this function.
That won't work either, because the color is set using a special character sequence that isn't recognized by the tabwriter
, so this row will be shorter by the length of twice the marker (one to set the color and one to get back to the standard color).
Write an alternative tabwriter (the algoerithm isn't even complex) that recognized the color character sequence and ignore it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With