Sobes.tech
Senior

Wie schreibt man parallele HTTP-Anfragen in Golang?

sobes.tech KI

Antwort von AI

In Go werden für parallele HTTP-Anfragen in der Regel Goroutines und Kanäle verwendet, um die Ergebnisse zu sammeln. Beispiel:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func fetch(url string, ch chan<- string) {
    resp, err := http.Get(url)
    if err != nil {
        ch <- fmt.Sprintf("error: %v", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        ch <- fmt.Sprintf("error reading body: %v", err)
        return
    }
    ch <- string(body)
}

func main() {
    urls := []string{
        "https://example.com",
        "https://golang.org",
        "https://httpbin.org/get",
    }

    ch := make(chan string)

    for _, url := range urls {
        go fetch(url, ch)
    }

    for range urls {
        fmt.Println(<-ch)
    }
}

Hier wird für jede URL eine Goroutine gestartet, die die HTTP-Anfrage durchführt und das Ergebnis in den Kanal sendet. Die Hauptfunktion liest so oft aus dem Kanal, wie Anfragen gestellt wurden, und sammelt alle Antworten parallel.