Skip to content

Instantly share code, notes, and snippets.

@owickstrom
Last active December 23, 2015 07:09
Show Gist options
  • Save owickstrom/6598436 to your computer and use it in GitHub Desktop.
Save owickstrom/6598436 to your computer and use it in GitHub Desktop.
Going Async in Go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
syslog, err := os.Open("/var/log/system.log")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer syslog.Close() // called after the for loop
scanner := bufio.NewScanner(syslog)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
package main
import "fmt"
func increased(source <-chan int) chan int {
increased := make(chan int)
go func() {
for {
increased <- (<-source + 1)
}
}()
return increased
}
func main() {
first := make(chan int)
var result = first
for i := 1; i <= 100000; i++ {
result = increased(result)
}
first <- 1
fmt.Printf("Result is %d", <-result)
}
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
package main
func main() {
// make a map
ages := make(map[string]int)
ages["John"] = 83
ages["Jane"] = 23
// now with a literal
phoneNumbers := map[string]string{"John": "555-GO-ROCKS", "Jane": "555-MAPS-TOO"}
// delete John's number
delete(phoneNumbers, "John")
}
package main
import (
"fmt"
"net/http"
"sync"
)
func get(url string, wg *sync.WaitGroup) {
defer wg.Done()
if _, err := http.Get(url); err != nil {
fmt.Println("Failed to get", url, err)
} else {
fmt.Println("Got", url)
}
}
func main() {
urls := []string{"http://google.com", "http://bing.com", "http://yahoo.com"}
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go get(url, &wg) // pass a pointer to wg
}
wg.Wait()
fmt.Println("All done!")
}
package main
func main() {
// a slices with an initial length of 2
persons := make([]string, 2)
persons[0] = "John"
persons[1] = "Jane"
// a slice can be declared and initialized with a literal
ages := []int{15,23,49,84}
// get sub-sequences using the slice operator
exceptFirstTwo := ages[2:] // including ages[2]
justFirstTwo := ages[:2] // not including ages[2]
}
package main
import (
"fmt"
"net/http"
"time"
)
func get(url string) chan string {
result := make(chan string)
go func() {
_, err := http.Get(url)
if err != nil {
result <- "Failed"
} else {
result <- "Success"
}
}()
return result
}
func main() {
select {
case result := <-get("http://whatever.herokuapp.com"):
fmt.Println(result)
case <- time.After(time.Millisecond * 500):
fmt.Println("That server is too god damn slow")
}
}
package main
func modify(names *[2]string) {
names[0] = "John Travolta"
}
func main() {
// a variable declared and initialized with explicit type
var firstName string = "John"
// using shorthand syntax and type inference
lastName := "Doe"
// a constant value
const weather = "rain"
names := [2]string{"Jackie Chan", "Mark Wahlberg"}
// passing pointers to variables
modify(&names)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment