-
-
Save scottfrazer/adee2eff211a82b3303b0152212bb84b to your computer and use it in GitHub Desktop.
Go Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Go's "hello world" */ | |
package main | |
import "fmt" | |
func main() { | |
fmt.Println("hello world") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Concurrent "hello world" */ | |
package main | |
import "fmt" | |
func main() { | |
go fmt.Println("hello world") // might not print! | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Correct concurrent "hello world" */ | |
package main | |
import "fmt" | |
import "sync" | |
func main() { | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go func() { | |
fmt.Println("hello world") | |
wg.Done() | |
}() | |
wg.Wait() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Your first deadlock */ | |
package main | |
func main() { | |
c := make(chan int) | |
c <- 1 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Your first deadlock, fixed */ | |
package main | |
func main() { | |
c := make(chan int) | |
go func() { <-c }() | |
c <- 1 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Your first deadlock, fixed with buffered channel */ | |
package main | |
func main() { | |
c := make(chan int, 1) | |
c <- 1 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Non-blocking waits */ | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
func sleeper(d time.Duration, wg *sync.WaitGroup) { | |
time.Sleep(d) | |
fmt.Printf("slept for %s\n", d) | |
wg.Done() | |
} | |
func main() { | |
var wg sync.WaitGroup | |
for i := 0; i < 1000; i++ { | |
wg.Add(1) | |
go sleeper(time.Second*time.Duration(rand.Int()%10), &wg) | |
} | |
wg.Wait() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Easy timeouts */ | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func consumer(c chan string) { | |
time.Sleep(time.Second * 2) | |
fmt.Printf("consume: %s\n", <-c) | |
} | |
func main() { | |
c := make(chan string) | |
go consumer(c) | |
select { | |
case <-time.After(time.Second * 1): | |
fmt.Println("timed out!") | |
case c <- "a message": | |
fmt.Println("sent a message") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Dead simple HTTP server */ | |
/* boom -n 1000 -c 100 http://localhost:8000 */ | |
package main | |
import ( | |
"io" | |
"net/http" | |
) | |
func MyHttpHandler(w http.ResponseWriter, r *http.Request) { | |
io.WriteString(w, `this is a response`) | |
} | |
func main() { | |
http.HandleFunc("/", MyHttpHandler) | |
http.ListenAndServe(":8000", nil) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* HTTP server with backpressure */ | |
/* http --form POST http://localhost:8000/ query=foobar */ | |
package main | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"time" | |
) | |
var work = make(chan string, 5) | |
func MyHttpHandler(w http.ResponseWriter, r *http.Request) { | |
query := r.FormValue("query") | |
timeout := time.Millisecond * 500 | |
select { | |
case work <- query: | |
io.WriteString(w, fmt.Sprintf("I've accepted your query: %s", query)) | |
case <-time.After(timeout): | |
w.Header().Set("Content-Type", "text/plain; charset=utf-8") | |
w.WriteHeader(http.StatusTooManyRequests) | |
io.WriteString(w, "Too many requests! Slow down!") | |
return | |
} | |
} | |
func main() { | |
http.HandleFunc("/", MyHttpHandler) | |
http.ListenAndServe(":8000", nil) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* The defer statement */ | |
package main | |
import "fmt" | |
import "sync" | |
var mutex sync.Mutex | |
func log(msg string) { | |
mutex.Lock() | |
defer mutex.Unlock() | |
if len(msg) == 0 { | |
return | |
} | |
fmt.Println(msg) | |
} | |
func main() { | |
log("hello") | |
log("") | |
log("world") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Non-blocking I/O */ | |
/* go run io.go server 1000000 1ms */ | |
/* go run io.go client 100 */ | |
package main | |
import ( | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"strconv" | |
"sync" | |
"time" | |
) | |
var mtx sync.Mutex | |
func log(format string, args ...interface{}) { | |
mtx.Lock() | |
defer mtx.Unlock() | |
fmt.Printf(format, args...) | |
} | |
func main() { | |
if os.Args[1] == "server" { | |
bytes, _ := strconv.ParseInt(os.Args[2], 10, 64) | |
sleep, _ := time.ParseDuration(os.Args[3]) | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
var hundredBytes = "abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxy" | |
for i := 0; i < int(bytes)/100; i++ { | |
io.WriteString(w, hundredBytes) | |
time.Sleep(sleep) | |
} | |
}) | |
fmt.Println("Listening on :9000 ...") | |
http.ListenAndServe(":9000", nil) | |
} | |
if os.Args[1] == "client" { | |
count, _ := strconv.ParseInt(os.Args[2], 10, 64) | |
var wg sync.WaitGroup | |
for i := 0; i < int(count); i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
start := time.Now() | |
resp, _ := http.Get("http://localhost:9000/") | |
defer resp.Body.Close() | |
body, _ := ioutil.ReadAll(resp.Body) | |
elapsed := time.Since(start) | |
log("Read %d bytes in %s\n", len(body), elapsed) | |
}() | |
} | |
wg.Wait() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment