Skip to content

Instantly share code, notes, and snippets.

View just1689's full-sized avatar
☁️
In the cloud

Justin Tamblyn just1689

☁️
In the cloud
  • South Africa
View GitHub Profile
@just1689
just1689 / main.go
Last active April 8, 2018 11:20
Convert values to futures
func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
@just1689
just1689 / main.go
Last active April 8, 2018 11:20
Process a channel of input and write results to a channel
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}
@just1689
just1689 / main.go
Last active April 8, 2018 11:20
Process data coming back later
func main() {
in := gen(2, 3)
// Distribute the sq work across two goroutines that both read from in.
c1 := sq(in)
c2 := sq(in)
// Consume the merged output from c1 and c2.
for n := range merge(c1, c2) {
fmt.Println(n) // 4 then 9, or 9 then 4
@just1689
just1689 / main.go
Last active April 8, 2018 11:19
Merge data from multiple channels
func merge(cs ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan int) {
for n := range c {
out <- n
}
@just1689
just1689 / main.go
Last active April 8, 2018 11:21
Waiting for another routine
func hello(done chan bool) {
fmt.Println("Hello world goroutine")
done <- true
}
func main() {
done := make(chan bool)
go hello(done)
<-done
fmt.Println("main function")
}
@just1689
just1689 / main.go
Last active April 8, 2018 11:21
Combining separate go routines results
// From https://golangbot.com/channels/
func calcSquares(number int, squareop chan int) {
sum := 0
for number != 0 {
digit := number % 10
sum += digit * digit
number /= 10
}
squareop <- sum
@just1689
just1689 / main.go
Last active April 8, 2018 11:21
Timeout channel
timeout := make(chan bool, 1)
go func() {
time.Sleep(1 * time.Second)
timeout <- true
}()
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
@just1689
just1689 / main.go
Last active April 8, 2018 11:20
Query multiple sources at once - return first
func Query(conns []Conn, query string) Result {
ch := make(chan Result)
for _, conn := range conns {
go func(c Conn) {
select {
case ch <- c.DoQuery(query):
default:
}
}(conn)
}
@just1689
just1689 / main.go
Last active April 8, 2018 11:20
Go routines communicating back and forth
package main
import "fmt"
func main() {
channel := make(chan int)
done := make(chan bool)
start := 0
go playerOne(channel, done)
@just1689
just1689 / deployment.yaml
Created September 11, 2018 22:57
Creating something and exposing it in K8s
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
run: my-nginx
replicas: 2
template: