Как работает net/http клиент?

Junior
1k просмотров
AFK Offer AI

Стандартный HTTP-клиент:

// Простой GET
resp, err := http.Get("https://api.example.com/users")
if err != nil {
    return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

Для production — создавай клиент с таймаутами:

client := &http.Client{
    Timeout: 10 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 10,
        IdleConnTimeout:     90 * time.Second,
    },
}

// POST с JSON data, _ := json.Marshal(user) req, _ := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+token)

resp, err := client.Do(req)

Важно: http.DefaultClient не имеет таймаута — запрос может висеть вечно. Всегда используй свой клиент. И всегда закрывай resp.Body.

Следующий вопрос

Способы оптимизации?