From 31f4a85605a6e2cf8168301449f1b04193fd98f1 Mon Sep 17 00:00:00 2001 From: Eddy Josue Hernandez Date: Mon, 21 Oct 2019 21:01:48 -0600 Subject: [PATCH] Fix functional options example --- idiom/functional-options.md | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/idiom/functional-options.md b/idiom/functional-options.md index 1e95086..f979b05 100644 --- a/idiom/functional-options.md +++ b/idiom/functional-options.md @@ -50,7 +50,7 @@ func Permissions(perms os.FileMode) Option { ```go package file -func New(filepath string, setters ...Option) error { +func New(filepath string, setters ...Option) (*os.File, error) { // Default Options args := &Options{ UID: os.Getuid(), @@ -66,29 +66,39 @@ func New(filepath string, setters ...Option) error { f, err := os.OpenFile(filepath, args.Flags, args.Permissions) if err != nil { - return err - } else { - defer f.Close() + return nil, err } + defer f.Close() if _, err := f.WriteString(args.Contents); err != nil { - return err + return nil, err } - return f.Chown(args.UID, args.GID) + f.Chown(args.UID, args.GID) + return f, nil } ``` ## Usage ```go -emptyFile, err := file.New("/tmp/empty.txt") -if err != nil { - panic(err) -} +func main() { + emptyFile, err := file.New("/tmp/empty.txt") + if err != nil { + panic(err) + } + fmt.Printf("file %v created\n", emptyFile.Name()) -fillerFile, err := file.New("/tmp/file.txt", file.UID(1000), file.Contents("Lorem Ipsum Dolor Amet")) -if err != nil { - panic(err) + fillerFile, err := file.New("/tmp/file.txt", file.UID(1000), file.Contents("Lorem Ipsum Dolor Amet")) + if err != nil { + panic(err) + } + fmt.Printf("file %v created\n", fillerFile.Name()) + + filePermissions, err := file.New("/tmp/file-permissions.txt", file.Permissions(0777), file.Contents("With Permissions 0777")) + if err != nil { + panic(err) + } + fmt.Printf("file %v created\n", filePermissions.Name()) } ```