Created
January 14, 2021 23:15
-
-
Save haleyrc/f03ac06c0a6b6b2d119866f634223ddb to your computer and use it in GitHub Desktop.
A simple wrapper around io.Writer that supresses output until a check function returns true. Could be useful when running a noisy command with exec.Cmd to keep it quiet until some pre-determined bit of output (think using Go to run a React application).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
func main() { | |
dw1 := NewDelayWriter(os.Stdout, nil) | |
fmt.Fprintln(dw1, "Hello!") | |
fmt.Fprintln(dw1, "Activate me") | |
fmt.Fprintln(dw1, "Hello again!") | |
dw2 := NewDelayWriter(os.Stdout, func(p []byte) (bool, error) { | |
s := strings.ToLower(string(p)) | |
if strings.Contains(s, "activate") { | |
return true, nil | |
} | |
return false, nil | |
}) | |
fmt.Fprintln(dw2, "Hello!") | |
fmt.Fprintln(dw2, "Activate me") | |
fmt.Fprintln(dw2, "Hello again!") | |
} | |
type CheckFunc func(p []byte) (shouldBeActive bool, err error) | |
func NewDelayWriter(w io.Writer, f CheckFunc) *DelayWriter { | |
dw := &DelayWriter{ | |
active: false, | |
w: w, | |
check: func(p []byte) (bool, error) { return false, nil }, | |
} | |
if f != nil { | |
dw.check = f | |
} | |
return dw | |
} | |
type DelayWriter struct { | |
active bool | |
w io.Writer | |
check func(p []byte) (bool, error) | |
} | |
func (dw *DelayWriter) Write(p []byte) (int, error) { | |
if !dw.active { | |
shouldBeActive, err := dw.check(p) | |
if err != nil { | |
return 0, err | |
} | |
dw.active = shouldBeActive | |
} | |
if !dw.active { | |
return 0, nil | |
} | |
return dw.w.Write(p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment