Skip to content

Commit

Permalink
Close files in loop
Browse files Browse the repository at this point in the history
Files/Requests opened in the loop are now closed after each iteration, not at the end.

Close #6
  • Loading branch information
cwww3 authored Oct 13, 2021
1 parent 4dde7ec commit 4e4f844
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 27 deletions.
44 changes: 26 additions & 18 deletions cmd/imgcat/imgcat.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,35 +36,43 @@ func main() {
} else {
for _, filename := range flag.Args() {
if strings.HasPrefix(filename, "http://") || strings.HasPrefix(filename, "https://") {
res, err := http.Get(filename)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()

if err := display(res.Body); err != nil {
log.Fatal(err)
}
displayNetPicture(filename)
} else {
// Skip errors and directories
if fi, err := os.Stat(filename); err != nil || fi.IsDir() {
continue
}

f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()

if err := display(f); err != nil {
log.Fatal(err)
}
displayLocalPicture(filename)
}
}
}
}

func displayNetPicture(filename string) {
res, err := http.Get(filename)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()

if err := display(res.Body); err != nil {
log.Fatal(err)
}
}

func displayLocalPicture(filename string) {
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()

if err := display(f); err != nil {
log.Fatal(err)
}
}

func display(r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
Expand Down
22 changes: 13 additions & 9 deletions cmd/imgls/imgls.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,23 @@ func main() {
continue
}

f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()

if err := display(filename, f); err != nil {
log.Fatal(err)
}
displayLocalPicture(filename)
}
}
}

func displayLocalPicture(filename string) {
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()

if err := display(filename, f); err != nil {
log.Fatal(err)
}
}

func display(filename string, r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
Expand Down

0 comments on commit 4e4f844

Please sign in to comment.