Skip to content

Commit

Permalink
feat: add sync errgroup to goutil package
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 18, 2022
1 parent 6a1054c commit dd9e08d
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/gookit/color v1.5.2
github.com/mattn/go-isatty v0.0.16
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
golang.org/x/sync v0.1.0
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261
golang.org/x/text v0.4.0
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHg
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 h1:Y/gsMcFOcR+6S6f3YeMKl5g+dZMEWqcz5Czj/GWYbkM=
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 h1:v6hYoSR9T5oet+pMXwUWkbiVqx/63mlHjefrHmxwfeY=
Expand Down
46 changes: 46 additions & 0 deletions group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package goutil

import (
"context"

"golang.org/x/sync/errgroup"
)

// ErrGroup is a collection of goroutines working on subtasks that
// are part of the same overall task.
//
// Refers:
//
// https://github.com/neilotoole/errgroup
// https://github.com/fatih/semgroup
type ErrGroup struct {
*errgroup.Group
}

// NewCtxErrGroup instance
func NewCtxErrGroup(ctx context.Context, limit ...int) (*ErrGroup, context.Context) {
egg, ctx1 := errgroup.WithContext(ctx)
if len(limit) > 0 && limit[0] > 0 {
egg.SetLimit(limit[0])
}

eg := &ErrGroup{Group: egg}
return eg, ctx1
}

// NewErrGroup instance
func NewErrGroup(limit ...int) *ErrGroup {
eg := &ErrGroup{Group: new(errgroup.Group)}

if len(limit) > 0 && limit[0] > 0 {
eg.SetLimit(limit[0])
}
return eg
}

// Add one or more handler at once
func (g *ErrGroup) Add(handlers ...func() error) {
for _, handler := range handlers {
g.Go(handler)
}
}

0 comments on commit dd9e08d

Please sign in to comment.