https://github.com/inv2004/errchan
Make (golang) Channels Great Again
https://github.com/inv2004/errchan
Last synced: about 1 year ago
JSON representation
Make (golang) Channels Great Again
- Host: GitHub
- URL: https://github.com/inv2004/errchan
- Owner: inv2004
- License: mit
- Created: 2024-12-28T22:47:59.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-05-26T23:21:29.000Z (about 1 year ago)
- Last Synced: 2025-05-27T00:27:09.151Z (about 1 year ago)
- Language: Go
- Homepage:
- Size: 38.1 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Make (golang) Channels Great Again
# `errchan.Chan`
The structure covers work with channels, context, cancellations and goroutine error-handling under the same hood
# Documentation
https://pkg.go.dev/github.com/inv2004/errchan
# Motivation
Golang channels are a powerful communication mechanism for goroutines. Unfortunately, there are some challenges in controlling, cancelling and handling errors using channels.
There are some helpers like https://pkg.go.dev/golang.org/x/sync/errgroup but the `errchan` mod also adds channels and context.
The main motivation is to have create a structure that can be returned as a channel from any function and takes care of all the stuff like creating, closing and error-control for the called goroutine, which can be difficult and tricky if you implement it using just basic types.
# Example:
https://go.dev/play/p/QktbZrM0CP0
```go
package main
import (
"context"
"errors"
"fmt"
"github.com/inv2004/errchan"
)
func reader(ctx context.Context) *errchan.Chan[int] {
ech, ctx := errchan.WithContext[int](ctx, 10)
ech.Go(func(ch chan<- int) error {
// ctx is unused here, because just one goroutine
for i := 1; i <= 3; i++ {
ch <- i
}
return errors.New("readerError")
})
return ech
}
func writer(ech *errchan.Chan[int]) (int, error) {
cnt := 0
for x := range ech.Chan() {
cnt++
if x == 3 {
return cnt, errors.New("writerError")
}
}
return cnt, nil
}
func main() {
ctx := context.Background()
ech := reader(ctx)
cnt, err := writer(ech)
fmt.Println(err) // writerError
fmt.Println(cnt) // 3
fmt.Println(ech.Err()) // readerError
}
```
# TODO
- Add `.SetLimit` to limit number of goroutines