-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
86 lines (68 loc) · 1.38 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package ex_test
import (
"database/sql"
"fmt"
"os"
"github.com/Seb-C/ex"
_ "github.com/mattn/go-sqlite3"
)
type FileRepository struct {
ex.Terminator
file *os.File
}
func NewFileRepository() (fileRepo *FileRepository, err error) {
fileRepo = &FileRepository{}
fileRepo.file, err = os.Create("data.json")
if err != nil {
return nil, err
}
fileRepo.Defer(fileRepo.file.Close)
fileRepo.Defer(func() error {
fmt.Println("closing FileRepository")
return nil
})
return fileRepo, nil
}
type DBRepository struct {
ex.Terminator
db *sql.DB
}
func NewDBRepository() (dbRepo *DBRepository, err error) {
dbRepo = &DBRepository{}
dbRepo.db, err = sql.Open("sqlite3", ":memory:")
if err != nil {
return nil, err
}
dbRepo.Defer(dbRepo.db.Close)
dbRepo.Defer(func() error {
fmt.Println("closing DBRepository")
return nil
})
return dbRepo, nil
}
type Service struct {
ex.Terminator
fileRepo *FileRepository
dbRepo *DBRepository
}
func NewService() (service *Service, err error) {
service = &Service{}
service.fileRepo, err = NewFileRepository()
if err != nil {
return nil, err
}
service.Defer(service.fileRepo.Close)
service.dbRepo, err = NewDBRepository()
if err != nil {
return nil, err
}
service.Defer(service.dbRepo.Close)
return service, nil
}
func Example() {
service, err := NewService()
if err != nil {
panic(err)
}
defer service.Close()
}