In Go, each concurrently executing activity is called a goroutine.
When a program starts, its only goroutine is the one that calls the main function. It's called the main_goroutine.
f() // call f(); wait for it to return
go f() // create a new goroutine that calls f(); don't wait
Channels
If goroutines are the activities of a concurrent Go program, channels are the connections between them.
A channel is a communication mechanism that lets one goroutine send values to another goroutine.
A channel is a reference to the data structure created by make
A channel has 2 operations, send and receive, also known as communications.
// Channels Examples
ch := make(chan int) // ch has type 'chan int'
ch <- x // a send statement
x = <-ch // a receive expression in an assignment statement
<-ch // a receive statement; result is discarded
close(ch) // To close a channel
Simple Web Server in Go
...
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
// handler echo the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}