Created
August 18, 2024 08:54
-
-
Save pmareke/13039d559c24428899d574f73a85ddc6 to your computer and use it in GitHub Desktop.
Echo script
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 ( | |
"flag" | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
var ( | |
n = flag.Bool("n", false, "omit trailing newline") | |
s = flag.String("s", " ", "separator") | |
) | |
func main() { | |
flag.Parse() | |
var out io.Writer = os.Stdout // CREATE A LOCAL WRITER CLASS | |
if err := echo(out, !*n, *s, flag.Args()); err != nil { // INJECT IT INTO THE ECHO FUNCTION | |
fmt.Fprintf(os.Stderr, "echo: %v\n", err) | |
os.Exit(1) | |
} | |
} | |
// RECIEVE OUT AS PARAMETER | |
func echo(out io.Writer, newline bool, sep string, args []string) error { | |
fmt.Fprint(out, strings.Join(args, sep)) | |
if newline { | |
fmt.Fprintln(out) | |
} | |
return nil | |
} |
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 ( | |
"bytes" | |
"fmt" | |
"testing" | |
) | |
func TestEcho(t *testing.T) { | |
var tests = []struct { | |
newline bool | |
sep string | |
args []string | |
want string | |
}{ | |
{true, "", []string{}, "\n"}, | |
{false, "", []string{}, ""}, | |
{true, "\t", []string{"one", "two", "three"}, "one\ttwo\tthree\n"}, | |
{true, ",", []string{"a", "b", "c"}, "a,b,c\n"}, | |
{false, ":", []string{"1", "2", "3"}, "1:2:3"}, | |
} | |
for _, test := range tests { | |
descr := fmt.Sprintf("echo(%v, %q, %q)", test.newline, test.sep, test.args) | |
var out = new(bytes.Buffer) // CREATE A WRITER LIKE CLASS JUST FOR THIS TEST | |
if err := echo(out, test.newline, test.sep, test.args); err != nil { // INJECT INTO ECHO FUNCTION | |
t.Errorf("%s failed: %v", descr, err) | |
continue | |
} | |
got := out.String() // READ OUTPUT | |
if got != test.want { | |
t.Errorf("%s = %q, want %q", descr, got, test.want) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment