Maison  >  Article  >  développement back-end  >  Goroutine fuit lors de la tentative de `ReadAll(response.Body)` où `response` est renvoyé par http `client.Do(...)`

Goroutine fuit lors de la tentative de `ReadAll(response.Body)` où `response` est renvoyé par http `client.Do(...)`

PHPz
PHPzavant
2024-02-09 23:06:18334parcourir

当尝试 `ReadAll(response.Body)` 时,goroutine 泄漏,其中 `response` 由 http `client.Do(...)` 返回

L'éditeur PHP Baicao a découvert une fuite de goroutine courante lors de la résolution de problèmes de programmation. Lorsque nous essayons d'utiliser `ReadAll(response.Body)`, l'objet `response` renvoyé est renvoyé par la méthode `client.Do(...)` du package `http`. Cependant, cette opération peut entraîner des problèmes de fuite des goroutines. Afin d'éviter que cela ne se produise, nous devons prendre certaines mesures pour gérer correctement les réponses http.

Contenu de la question

Cette question provient d'un scénario très courant où tous les octets sont lus à partir du corps de la réponse après un appel de méthode http.

Avec l'aide de https://github.com/uber-go/goleak, j'ai découvert une fuite de goroutine intéressante.

Pour démontrer le problème, utilisez go test 运行以下测试代码,这会导致 found 出现意外的 goroutine :

package main

import (
    "io"
    "net/http"
    "testing"

    "go.uber.org/goleak"
    "gotest.tools/v3/assert"
)

func testleak(t *testing.t) {
    defer goleak.verifynone(t)

    request, err := http.newrequest(http.methodget, "https://google.com", nil)
    assert.nilerror(t, err)

    client := http.client{}

    response, err := client.do(request)
    assert.nilerror(t, err)

    defer response.body.close()

    _, err = io.readall(response.body)

    assert.nilerror(t, err)
}

Sortie du test complet :

$ go test
--- FAIL: TestLeak (1.26s)
    main_test.go:28: found unexpected goroutines:
        [Goroutine 14 in state IO wait, with internal/poll.runtime_pollWait on top of the stack:
        goroutine 14 [IO wait]:
        internal/poll.runtime_pollWait(0x7f945c1e0398, 0x72)
                /home/wxh/.local/go/src/runtime/netpoll.go:305 +0x89
        internal/poll.(*pollDesc).wait(0xc000154280?, 0xc0000ca000?, 0x0)
                /home/wxh/.local/go/src/internal/poll/fd_poll_runtime.go:84 +0x32
        internal/poll.(*pollDesc).waitRead(...)
                /home/wxh/.local/go/src/internal/poll/fd_poll_runtime.go:89
        internal/poll.(*FD).Read(0xc000154280, {0xc0000ca000, 0x2000, 0x2000})
                /home/wxh/.local/go/src/internal/poll/fd_unix.go:167 +0x25a
        net.(*netFD).Read(0xc000154280, {0xc0000ca000?, 0xc00017edd8?, 0xc0004d5808?})
                /home/wxh/.local/go/src/net/fd_posix.go:55 +0x29
        net.(*conn).Read(0xc00009c000, {0xc0000ca000?, 0xc0000c68f0?, 0x2c?})
                /home/wxh/.local/go/src/net/net.go:183 +0x45
        crypto/tls.(*atLeastReader).Read(0xc0002d4138, {0xc0000ca000?, 0x0?, 0x29f6540f238f2947?})
                /home/wxh/.local/go/src/crypto/tls/conn.go:787 +0x3d
        bytes.(*Buffer).ReadFrom(0xc0000a0278, {0x7c3860, 0xc0002d4138})
                /home/wxh/.local/go/src/bytes/buffer.go:202 +0x98
        crypto/tls.(*Conn).readFromUntil(0xc0000a0000, {0x7c3b80?, 0xc00009c000}, 0xc0000a41c0?)
                /home/wxh/.local/go/src/crypto/tls/conn.go:809 +0xe5
        crypto/tls.(*Conn).readRecordOrCCS(0xc0000a0000, 0x0)
                /home/wxh/.local/go/src/crypto/tls/conn.go:616 +0x116
        crypto/tls.(*Conn).readRecord(...)
                /home/wxh/.local/go/src/crypto/tls/conn.go:582
        crypto/tls.(*Conn).Read(0xc0000a0000, {0xc0001cf000, 0x1000, 0x11?})
                /home/wxh/.local/go/src/crypto/tls/conn.go:1287 +0x16f
        bufio.(*Reader).Read(0xc0001af1a0, {0xc0001aad60, 0x9, 0xc0004d5d18?})
                /home/wxh/.local/go/src/bufio/bufio.go:237 +0x1bb
        io.ReadAtLeast({0x7c3760, 0xc0001af1a0}, {0xc0001aad60, 0x9, 0x9}, 0x9)
                /home/wxh/.local/go/src/io/io.go:332 +0x9a
        io.ReadFull(...)
                /home/wxh/.local/go/src/io/io.go:351
        net/http.http2readFrameHeader({0xc0001aad60?, 0x9?, 0xc0004d5df0?}, {0x7c3760?, 0xc0001af1a0?})
                /home/wxh/.local/go/src/net/http/h2_bundle.go:1565 +0x6e
        net/http.(*http2Framer).ReadFrame(0xc0001aad20)
                /home/wxh/.local/go/src/net/http/h2_bundle.go:1829 +0x95
        net/http.(*http2clientConnReadLoop).run(0xc0004d5f98)
                /home/wxh/.local/go/src/net/http/h2_bundle.go:8875 +0x130
        net/http.(*http2ClientConn).readLoop(0xc00009e180)
                /home/wxh/.local/go/src/net/http/h2_bundle.go:8771 +0x6f
        created by net/http.(*http2Transport).newClientConn
                /home/wxh/.local/go/src/net/http/h2_bundle.go:7478 +0xaaa
        
         Goroutine 37 in state IO wait, with internal/poll.runtime_pollWait on top of the stack:
        goroutine 37 [IO wait]:
        internal/poll.runtime_pollWait(0x7f945c1e02a8, 0x72)
                /home/wxh/.local/go/src/runtime/netpoll.go:305 +0x89
        internal/poll.(*pollDesc).wait(0xc0003ca000?, 0xc000202000?, 0x0)
                /home/wxh/.local/go/src/internal/poll/fd_poll_runtime.go:84 +0x32
        internal/poll.(*pollDesc).waitRead(...)
                /home/wxh/.local/go/src/internal/poll/fd_poll_runtime.go:89
        internal/poll.(*FD).Read(0xc0003ca000, {0xc000202000, 0x1300, 0x1300})
                /home/wxh/.local/go/src/internal/poll/fd_unix.go:167 +0x25a
        net.(*netFD).Read(0xc0003ca000, {0xc000202000?, 0xc0004e6798?, 0xc0004c0808?})
                /home/wxh/.local/go/src/net/fd_posix.go:55 +0x29
        net.(*conn).Read(0xc000014028, {0xc000202000?, 0xc000136630?, 0x2c?})
                /home/wxh/.local/go/src/net/net.go:183 +0x45
        crypto/tls.(*atLeastReader).Read(0xc000276288, {0xc000202000?, 0x0?, 0x150fbb8ccb566149?})
                /home/wxh/.local/go/src/crypto/tls/conn.go:787 +0x3d
        bytes.(*Buffer).ReadFrom(0xc0000a0978, {0x7c3860, 0xc000276288})
                /home/wxh/.local/go/src/bytes/buffer.go:202 +0x98
        crypto/tls.(*Conn).readFromUntil(0xc0000a0700, {0x7c3b80?, 0xc000014028}, 0xc0004cc2c0?)
                /home/wxh/.local/go/src/crypto/tls/conn.go:809 +0xe5
        crypto/tls.(*Conn).readRecordOrCCS(0xc0000a0700, 0x0)
                /home/wxh/.local/go/src/crypto/tls/conn.go:616 +0x116
        crypto/tls.(*Conn).readRecord(...)
                /home/wxh/.local/go/src/crypto/tls/conn.go:582
        crypto/tls.(*Conn).Read(0xc0000a0700, {0xc00023c000, 0x1000, 0x11?})
                /home/wxh/.local/go/src/crypto/tls/conn.go:1287 +0x16f
        bufio.(*Reader).Read(0xc00022a2a0, {0xc00020e2e0, 0x9, 0xc0004c0d18?})
                /home/wxh/.local/go/src/bufio/bufio.go:237 +0x1bb
        io.ReadAtLeast({0x7c3760, 0xc00022a2a0}, {0xc00020e2e0, 0x9, 0x9}, 0x9)
                /home/wxh/.local/go/src/io/io.go:332 +0x9a
        io.ReadFull(...)
                /home/wxh/.local/go/src/io/io.go:351
        net/http.http2readFrameHeader({0xc00020e2e0?, 0x9?, 0xc0004c0df0?}, {0x7c3760?, 0xc00022a2a0?})
                /home/wxh/.local/go/src/net/http/h2_bundle.go:1565 +0x6e
        net/http.(*http2Framer).ReadFrame(0xc00020e2a0)
                /home/wxh/.local/go/src/net/http/h2_bundle.go:1829 +0x95
        net/http.(*http2clientConnReadLoop).run(0xc0004c0f98)
                /home/wxh/.local/go/src/net/http/h2_bundle.go:8875 +0x130
        net/http.(*http2ClientConn).readLoop(0xc00019e300)
                /home/wxh/.local/go/src/net/http/h2_bundle.go:8771 +0x6f
        created by net/http.(*http2Transport).newClientConn
                /home/wxh/.local/go/src/net/http/h2_bundle.go:7478 +0xaaa
        ]
FAIL
exit status 1

Est-ce que quelqu'un sait comment résoudre ce problème ?

Merci !

Solution de contournement

Dans Go, http.Client utilise Transport (interface http.RoundTripper). http.Transport est son implémentation par défaut. Le http.Transfer par défaut maintient un pool de connexions qui contient les connexions qui restent actives ou inactives pour une raison quelconque.

En gros, tout ce que vous avez à faire est de vous assurer qu'il n'y a aucune connexion dans la piscine lorsque vous appelez goleak.Verify*

Cela peut être fait par :

  1. Désactivez le maintien de la vie pour tous les clients http avant d'exécuter une requête :
    client := http.Client{Transport: &http.Transport{DisableKeepAlive: true}}
  2. Fermez les connexions inactives * avant d'appeler goleak.Verify :
    client.CloseIdleConnections() // Disponible depuis Go 1.12

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer