Skip to content

Instantly share code, notes, and snippets.

View ankur22's full-sized avatar

Ankur ankur22

View GitHub Profile
@ankur22
ankur22 / structEmbedding.go
Created May 30, 2020 13:29
Example of struct embedding
package main
import (
"log"
)
type logger struct{}
func (l *logger) do(in string) {
log.Println(in)
@ankur22
ankur22 / interfaceEmbedding.go
Last active May 30, 2020 13:12
Example of interface embedding where two functions are defined with different signatures
type doer interface {
do(string)
}
type validator interface {
validate(string) bool
do(int)
}
type doerAndValidator interface {
@ankur22
ankur22 / interfaceEmbedding.go
Created May 30, 2020 13:06
Example of interface embedding where two interfaces define the same function
type doer interface {
do(string)
}
type validator interface {
validate(string) bool
do(string)
}
type doerAndValidator interface {
@ankur22
ankur22 / interfaceEmbedding.go
Created May 30, 2020 12:55
A very simple example of working with embedded interfaces
package main
import (
"log"
)
type doer interface {
do(string)
}
@ankur22
ankur22 / embedding.go
Last active August 19, 2020 02:20
Retryable HTTP Client using embedded structs and the decorator pattern
package main
import (
"fmt"
"log"
"net/http"
"github.com/cenkalti/backoff/v4"
)
@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:
@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 / 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 / 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 / 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()