15. Goroutines
• Goroutines are like lightweight threads.
• They start with tiny stacks and resize as needed.
• Go programs can have hundreds of thousands of them.
• Start a goroutine using the go statement: go f(args)
• The Go runtime schedules goroutines onto OS threads.
15
18. Hello, World
again
package main
import "fmt"
func main() {
ch := sayHello("World")
for str := range ch {
fmt.Println(str)
}
}
func sayHello(name string) <-chan string {
ch := make(chan string)
go func() {
defer close(ch)
ch <- "Hello"
ch <- name
}()
return ch;
}
18
19. Select
• A select statement blocks until communication can proceed.
select {
case n := <-foo:
fmt.Println("received from foo", n)
case n := <-bar:
fmt.Println("received from bar", n)
case <- time.After(10 * time.Second)
fmt.Println("time out")
}
19
21. Hello, World
again
package main
import "fmt"
func main() {
var ch = sayHello("World")
for str := range ch {
fmt.Println(str)
}
}
func sayHello(name string) <-chan string {
ch := make(chan string)
go func() {
defer close(ch)
ch <- "Hello"
ch <- name
}()
return ch;
}
21
22. Struct
• Control over memory layout
• Value vs. pointer (reference)
type Example struct {
Number int
Data [128]byte
Payload struct{
Length int
Checksum int
}
}
22
func (e *Example) String() string {
if e == nil {
return "N/A"
}
return fmt.Sprintf("Example %d", e.Number)
}
29. Design Secure Store for LSDC
• Listen on API calls from other micro-services
• While got a request...
• Run a handler function in a new Goroutine to handle this request
• Pass a channel (context) to control request timeout
• Back to main loop, waiting for next request
• The hander function does:
• For PUT: encrypt the secret with KMS, put it into DynamoDB
• For GET: query it from DynamoDB, decrypt secret with KMS
29