Go

Go programming language

https://go.dev/

This Go snippet demonstrates Goroutines, Channels, Pipelines, and native HTTP/TCP support.

•	Goroutines: Lightweight threads managed by Go, created with go func(). They let you run tasks concurrently.
•	Channels: Typed pipes that let goroutines safely communicate. You can send (ch <- val) and receive (val := <-ch) data without locks.
•	Pipelines: A series of goroutines connected by channels. Each stage processes data and passes it to the next, enabling clean, concurrent workflows.
•   First-class HTTP/TCP support in Go’s standard library.
 1
 2package main
 3
 4import (
 5    "fmt"
 6    "net/http"
 7)
 8
 9// func generate sends each URL on a channel and then closes it.
10func generate(urls ...string) <-chan string {
11    // create a channel of strings
12    out := make(chan string)
13    // launch an anonymous function as a goroutine
14    go func() {
15        // ensure channel is closed when done
16        defer close(out)
17        // send each URL into the channel
18        for _, url := range urls {
19            out <- url
20        }
21    }() // immediately invoke the anonymous func
22    return out
23}
24
25// func fetch takes URLs from in, HTTP-GETs them, and outputs status codes.
26func fetch(in <-chan string) <-chan int {
27    // create a channel of ints
28    out := make(chan int)
29    // run the loop concurrently
30    go func() {
31        // close when finished
32        defer close(out)
33        // receive each URL until input channel closes
34        for url := range in {
35            // HTTP GET via standard library
36            resp, err := http.Get(url)
37            if err != nil {
38                fmt.Println("error fetching", url, err)
39                continue
40            }
41            // send the status code into the channel
42            out <- resp.StatusCode
43            resp.Body.Close()
44        }
45    }()
46    return out
47}
48
49func main() {
50    // Stage 1: generate URLs
51    urls := generate(
52        "https://golang.org",
53        "https://example.com",
54    )
55
56    // Stage 2: fetch each URL’s status code
57    statuses := fetch(urls)
58
59    // Stage 3: print results
60    for code := range statuses {
61        fmt.Println("Status code:", code)
62    }
63}