From ac9a81d3e7efc515fa3f75c1b207895c7ca21d08 Mon Sep 17 00:00:00 2001 From: Adphi Date: Tue, 3 Mar 2020 14:54:53 +0100 Subject: [PATCH] gorm db openned in options --- service/options.go | 6 +++++- service/service.go | 10 +++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/service/options.go b/service/options.go index 50335ae..ac35179 100644 --- a/service/options.go +++ b/service/options.go @@ -144,9 +144,11 @@ func WithKey(path string) Option { } } -func WithDB(db *gorm.DB) Option { +func WithDB(dialect string, args ...interface{}) Option { + db, err := gorm.Open(dialect, args...) return func(o *options) { o.db = db + o.error = err } } @@ -236,6 +238,8 @@ type options struct { clientInterceptors []grpc.UnaryClientInterceptor streamClientInterceptors []grpc.StreamClientInterceptor + + error error } func (o *options) Name() string { diff --git a/service/service.go b/service/service.go index 690121a..c903008 100644 --- a/service/service.go +++ b/service/service.go @@ -8,6 +8,7 @@ import ( grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware" "github.com/jinzhu/gorm" "github.com/spf13/cobra" + "go.uber.org/multierr" "google.golang.org/grpc" ) @@ -45,6 +46,9 @@ func newService(opts ...Option) (*service, error) { for _, f := range opts { f(s.opts) } + if s.opts.error != nil { + return nil, s.opts.error + } go func() { for { select { @@ -144,5 +148,9 @@ func (s *service) Stop() error { func (s *service) Close() error { s.mu.Lock() defer s.mu.Unlock() - return s.Stop() + err := multierr.Combine(s.Stop()) + if s.opts.db != nil { + err = multierr.Append(s.opts.db.Close(), err) + } + return err }