发布时间:2024-11-22 03:12:57
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
urls := []string{
"http://www.example.com",
"http://www.google.com",
"http://www.github.com",
}
for _, url := range urls {
go func(url string) {
resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error fetching %s: %v\n", url, err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading body of %s: %v\n", url, err)
return
}
fmt.Printf("Size of %s: %d\n", url, len(body))
}(url)
}
// 等待所有协程完成
time.Sleep(time.Second)
}
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
package main
import (
"fmt"
"time"
)
func worker(id int, tasks <-chan int, results chan<- int) {
for task := range tasks {
fmt.Printf("Worker %d started task %d\n", id, task)
time.Sleep(time.Second)
fmt.Printf("Worker %d finished task %d\n", id, task)
results <- task * 2
}
}
func main() {
tasks := make(chan int, 10)
results := make(chan int, 10)
for i := 0; i < 3; i++ {
go worker(i, tasks, results)
}
for i := 0; i < 10; i++ {
tasks <- i
}
close(tasks)
for i := 0; i < 10; i++ {
result := <-results
fmt.Printf("Result %d\n", result)
}
}