Skip to content

Instantly share code, notes, and snippets.

View ankur22's full-sized avatar

Ankur ankur22

View GitHub Profile
@ankur22
ankur22 / Step1.go
Last active April 10, 2020 18:33
TDD and Golang
// Step 1: Write a failing test
func TestURLShortner(t *testing.T) {
var tests = []struct {
name, in, expected string
err error
}{
{"NoScheme", "https://google.com", "1", nil},
{"NoScheme", "google", "", errors.New("invalid")},
}
@ankur22
ankur22 / Closing channel and context
Last active May 8, 2020 20:14
Goroutines, Channels, Contexts, Timers, Errgroups and Waitgroups
lines := make(chan string, 1)
go func() {
defer close(lines)
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
break
}
lines <- scanner.Text()
@ankur22
ankur22 / ctxcancel.go
Created May 8, 2020 19:47
Context with cancel
ctx, cancel := context.WithCancel(context.Background())
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Printf("Caught %s\n", sig)
cancel()
}()
@ankur22
ankur22 / chanok.go
Created May 8, 2020 19:50
Working with ok var from the channel
lines := make(chan string, 1)
go func() {
defer close(lines)
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
break
}
lines <- scanner.Text()
@ankur22
ankur22 / waitgroup.go
Last active May 8, 2020 19:52
Using WaitGroup
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer func() {
wg.Done()
close(lines)
}()
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
@ankur22
ankur22 / errgroup.go
Created May 8, 2020 19:53
Using errgroup
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
defer close(lines)
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
break
}
lines <- scanner.Text()
@ankur22
ankur22 / timer.go
Last active May 8, 2020 19:54
Using timer to identify slow writes to a channel
eg.Go(func() error {
defer close(lines)
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
break
}
lines <- scanner.Text()
time.Sleep(time.Second) // To fake the slow writing to the lines channel
@ankur22
ankur22 / range.go
Created May 8, 2020 19:55
Using range over a channel
eg.Go(func() error {
for l := range lines {
select {
case <-ctx.Done():
fmt.Println("Sender: Context closed")
return ctx.Err()
default:
fmt.Printf("Sender: Sending %s to remote database\n", l)
}
}
@ankur22
ankur22 / done.go
Last active May 8, 2020 20:13
Retrieving the done channel prior to using it in the goroutine
done := ctx.Done()
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
defer close(lines)
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
break
}
lines <- scanner.Text()
@ankur22
ankur22 / timer.go
Created May 8, 2020 20:01
Reusing the timer
timeout := time.Millisecond * 500
timeoutTimer := time.NewTimer(timeout)
defer timeoutTimer.Stop()
eg.Go(func() error {
for {
select {
case <-done():
fmt.Println("Sender: Context closed")
return ctx.Err()
case <-timeoutTimer.C: