1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-25 14:36:06 +03:00

Fix functional options example

This commit is contained in:
Eddy Josue Hernandez 2019-10-21 21:01:48 -06:00
parent f978e42036
commit 31f4a85605

View File

@ -50,7 +50,7 @@ func Permissions(perms os.FileMode) Option {
```go ```go
package file package file
func New(filepath string, setters ...Option) error { func New(filepath string, setters ...Option) (*os.File, error) {
// Default Options // Default Options
args := &Options{ args := &Options{
UID: os.Getuid(), UID: os.Getuid(),
@ -66,29 +66,39 @@ func New(filepath string, setters ...Option) error {
f, err := os.OpenFile(filepath, args.Flags, args.Permissions) f, err := os.OpenFile(filepath, args.Flags, args.Permissions)
if err != nil { if err != nil {
return err return nil, err
} else {
defer f.Close()
} }
defer f.Close()
if _, err := f.WriteString(args.Contents); err != nil { 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 ## Usage
```go ```go
emptyFile, err := file.New("/tmp/empty.txt") func main() {
if err != nil { emptyFile, err := file.New("/tmp/empty.txt")
if err != nil {
panic(err) 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")) fillerFile, err := file.New("/tmp/file.txt", file.UID(1000), file.Contents("Lorem Ipsum Dolor Amet"))
if err != nil { if err != nil {
panic(err) 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())
} }
``` ```