Goroutines
A goroutine is a lightweight thread managed by Go. Start one with the go keyword.
package main
import (
"fmt"
"sync"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("worker", id, "working")
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait() // wait until all workers finish
}Channels
Channels let goroutines communicate safely.
ch := make(chan int)
go func() {
for i := 1; i <= 3; i++ {
ch <- i * 10 // send
}
close(ch)
}()
for v := range ch { // receive until closed
fmt.Println(v)
}A Go proverb: do not communicate by sharing memory; share memory by communicating.
Protecting shared data
var mu sync.Mutex
var counter int
mu.Lock()
counter++
mu.Unlock()Run go run -race main.go to detect data races.
A tiny web server
package main
import (
"encoding/json"
"log"
"net/http"
)
type Message struct {
Text string `json:"text"`
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Message{Text: "Hello from Go!"})
}
func main() {
http.HandleFunc("/hello", hello)
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}Run it and open http://localhost:8080/hello.
Next steps
Add a POST handler that reads JSON with json.NewDecoder(r.Body).Decode(&v), store items in a slice protected by a mutex, and then connect a database. Try packages such as database/sql.
Practice
Build a to-do API with GET /todos and POST /todos and test it with your browser or a tool like curl.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Start two goroutines and wait with a WaitGroup.
- Send values over a channel.
- Create an HTTP server that returns text at /hello.
Common mistakes
- Exiting main before goroutines finish.
- Sharing data between goroutines without synchronisation.
Quick check
What is a goroutine?
A lightweight function running concurrently.
What are channels for?
Communication between goroutines.