Skip to content

Commit 7285c6a

Browse files
committed
handle errors and refactor
1 parent 1c41d8c commit 7285c6a

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

main.go

+12-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"archive/zip"
5-
"fmt"
65
"io"
76
"os"
87
)
@@ -16,10 +15,19 @@ func NewArchiver(archive *os.File) *Archiver {
1615
return &Archiver{Dest: archive, w: zip.NewWriter(archive)}
1716
}
1817

19-
func (a *Archiver) Archive(r io.Reader) {
20-
writer, _ := a.w.Create("hello.txt")
21-
fmt.Fprint(writer, r)
18+
func (a *Archiver) Archive(r io.Reader) error {
19+
writer, err := a.w.Create("hello.txt")
20+
if err != nil {
21+
return err
22+
}
23+
24+
_, err = io.Copy(writer, r)
25+
if err != nil {
26+
return err
27+
}
28+
2229
a.w.Close()
30+
return nil
2331
}
2432

2533
func main() {

main_test.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"bytes"
66
"fmt"
77
"os"
8+
"strings"
89
"testing"
910

1011
"github.com/alecthomas/assert/v2"
@@ -31,7 +32,8 @@ func TestArchive(t *testing.T) {
3132
})
3233

3334
t.Run("archives a single non-empty file called hello.txt", func(t *testing.T) {
34-
file := bytes.NewBufferString("hello, world!")
35+
fileContent := "hello, world!"
36+
file := strings.NewReader(fileContent)
3537
archive, cleanup := createTempArchive(t, archivePath)
3638
defer cleanup()
3739

@@ -42,7 +44,7 @@ func TestArchive(t *testing.T) {
4244
defer archiveReader.Close()
4345

4446
got := archiveReader.File[0].UncompressedSize64
45-
want := uint64(file.Len())
47+
want := uint64(len(fileContent))
4648

4749
assert.Equal(t, want, got, "expected %s to have size %d but got %d", "hello.txt", want, got)
4850
})

0 commit comments

Comments
 (0)