Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Created August 9, 2014 04:56
Show Gist options
  • Save kracekumar/93eb9480161ad4214036 to your computer and use it in GitHub Desktop.
Save kracekumar/93eb9480161ad4214036 to your computer and use it in GitHub Desktop.
Go lang hands on at 6th docker meetup bangalore http://www.meetup.com/Docker-Bangalore/events/194813972/
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func basics() {
// Print to "Welcome to 6th docker meetup" stdout
// Say about capital letter
// Variable
// Show with var and without var
// show example with int and string
// Constants
// show Printf and Println with %v
// For loop
// No while loop, infinite for loop with break
// Create new function called add which will take two parameters
// Call function with arguments
// Create a function called sum which will take any number of arguments
// Call Without args
// Call with varying args
// Create Arrays with fixed sizes
// Create slices like []int{1, 2, 3} and also show make
// [:]
// Loop over arrays with range, say about _
// Print them using %v
// show hashmap with string as keys and bool as value
// make(map[string]bool)
// map[string]bool{"foo": true, "bar": false}
// Iterate over the map
// Delete the key
// Delete is not atomic in hash map. Acquire mutex before deleting
// Simple struct example
}
// Write func add which takes two integer arguments and returns int
// Write func sum which takes infinite number of arguments and returns int
// Show return without argument
// Write a function generateRandomNumbers which takes total numbers to produce
// and returns int channel. Use go routine to send message in the channel
// Close the channel once messages are sent
// Write a function to filter numbers divisible by 5 which takes int channel
// as an argument and returns string channel.
// Iterate over the channel using range to receive the messages.
// Close the channel after all message are sent.
func main() {
// Show godoc, godoc -http:=6060
// Show some go lang syntax et all.
basics()
// Now basic producer, consumer problem.
// Generate list of 1000 numbers and filter multiple of 5's
// Time usual blocking solution
// start := time.Now()
// Use anonymous function to execute the code
// fmt.Println("blocking filter for 1000 nos took", time.Since(start))
// Generate 1000 numbers and filter numbers divisible by 5 using go routine like pipeline
// start = time.Now()
// Call the function generateNumbers which will return int channel
// Call the function filterDivisibleby5 which will return string channel
// Loop over the string channel and print the message
// fmt.Println("Pipeline filter for 1000 nos took", time.Since(start))
// Generate 1000 numbers using go routine and consume them and filter
// inside for loop using int channel.
// start = time.Now()
// fmt.Println("Inline goroutine filter for 1000 nos took", time.Since(start))
// Compare three solutions.
// Write a web crawler to fetch web pages in blocking fashion
// start = time.Now()
// urls := []string{
// "http://localhost:6060/doc/",
// "http://localhost:6060/pkg/",
// "http://localhost:6060/project/",
// "http://localhost:6060/help/",
// "http://localhost:6060/blog/",
// }
// Use net/http to fetch the web page and check for error
// fmt.Printf("Time taken to fetch %v urls is %v\n", len(urls),
// time.Since(start))
// Repeat the same problem using Go routine and sync.WaitGroup
// var wg sync.WaitGroup
// start = time.Now()
// Use for loop to iterate over the urls
// Don't forget to decerement waitgroup with wg.Done()
// Comment this and show the difference
// wg.Wait()
// fmt.Printf("Time taken to fetch %v urls using go routines is %v\n", len(urls), time.Since(start))
}
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func basics() {
// Print to stdout
// Note capital letter
fmt.Println("Welcome to 6th docker meetup")
// Variable
age := 24
var year int = 2014
var name string = "Kracekumar"
// Constants
const duration = 60
fmt.Printf("Instructor is %v %v\n", name, age)
fmt.Println(year)
fmt.Println("Duration is ", duration, "min")
// For loop
for i := 1; i <= 3; i++ {
fmt.Println(i)
}
// No while loop
i := 1
for {
fmt.Println(i)
// if condition
if i > 5 {
break
}
i++
}
// Call function with arguments
fmt.Println(add(2, 33))
// function with n number of arguments
sum() // Without args
fmt.Println(sum(1, 2, 3)) // variadic args
// Arrays
nums := []int{1, 2, 3}
var nos [5]int
for i := 0; i < 5; i++ {
nos[i] = i * i
}
fmt.Printf("Squared %v\n", nos)
fmt.Printf("Arrays %v\n", nums)
// hashmap
urls := make(map[string]bool)
urls["http://kracekumar.com"] = false
urls["https://golang.org"] = true
urls["https://python.org"] = true
for key, val := range urls {
fmt.Println(key, val)
}
delete(urls, "https://kracekumar.com")
fmt.Println(urls, len(urls))
// Struct
type Person struct {
name string
salary float64
}
var p Person
p = Person{"Rob pike", 100000.34}
fmt.Println(p)
s := &p
s.name = "Kracekumar"
fmt.Println(s, p)
}
func add(a, b int) int {
return a + b
}
func sum(nums ...int) (total int) {
fmt.Println(nums)
total = 0
for _, val := range nums {
total += val
}
return
}
func generateRandomNumbers(n int) <-chan int {
out := make(chan int)
go func() {
for i := 0; i < n; i++ {
out <- i
}
close(out)
}()
return out
}
func filterDivisibleBy5(to_receive <-chan int) <-chan string {
out := make(chan string)
go func() {
for no := range to_receive {
if no%5 == 0 {
fmt.Printf("-")
}
}
close(out)
}()
return out
}
func main() {
// Show godoc, godoc -http:=6060
// Show some go lang syntax et all.
basics()
// Now basic producer, consumer problem.
// Generate list of 1000 random numbers and filter multiple of 5's
// Time usual blocking solution
start := time.Now()
func() {
for i := 0; i < 1000; i++ {
if i%5 == 0 {
fmt.Printf(".")
}
}
}()
fmt.Println("blocking filter for 1000 nos took", time.Since(start))
// Time go routine solution
start = time.Now()
out := generateRandomNumbers(1000)
messages := filterDivisibleBy5(out)
for msg := range messages {
fmt.Printf(msg)
}
fmt.Println("Pipeline filter for 1000 nos took", time.Since(start))
// Go routine concept
start = time.Now()
out2 := make(chan int)
go func() {
for i := 0; i < 1000; i++ {
out2 <- i
}
close(out2)
}()
for no := range out2 {
if no%5 == 0 {
fmt.Printf(".")
}
}
fmt.Println("Inline goroutine filter for 1000 nos took", time.Since(start))
// Write a web crawler to fetch web pages
start = time.Now()
urls := []string{
"http://localhost:6060/doc/",
"http://localhost:6060/pkg/",
"http://localhost:6060/project/",
"http://localhost:6060/help/",
"http://localhost:6060/blog/",
}
for _, url := range urls {
_, err := http.Get(url)
if err != nil {
fmt.Println(err, url)
}
}
fmt.Printf("Time taken to fetch %v urls is %v\n", len(urls), time.Since(start))
// Go routine solution
var wg sync.WaitGroup
start = time.Now()
for _, url := range urls {
// Increment the WaitGroup counter.
wg.Add(1)
// Launch a goroutine to fetch the URL.
go func(url string) {
// Decrement the counter when the goroutine completes.
defer wg.Done()
// Fetch the URL.
_, err := http.Get(url)
// fmt.Println(resp)
if err != nil {
fmt.Println(err, url)
}
}(url)
}
// Comment this and show the difference
wg.Wait()
fmt.Printf("Time taken to fetch %v urls using go routines is %v\n", len(urls), time.Since(start))
}
@kracekumar
Copy link
Author

instructions.go contains all the instruction for the workshop steps as comments. The solution is under workshop.go

@originalankur
Copy link

// Struct
type Person struct {
name string
salary float64
}

May be you can put a comment explaining the significance of upper/lower case naming convention.
i.e. Go determines whether a particular identifier is public / private within package context. When you changed the fields to be upper case, they become public so can be exported.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment