Standard library / net/http
http.Transport.CloseIdleConnections()
Close idle pooled connections without interrupting active requests. The next request may establish a new connection. Expected stdout: 'true\n'.
Formal Syntax & Structure
go syntaxgo
func (t *Transport) CloseIdleConnections()Working Example
Example Snippetgo
package main
import ( "fmt" "io" "net/http" "net/http/httptest" "net/http/httptrace")
func main() { s := fixture() defer s.Close() tr := &http.Transport{} c := &http.Client{Transport: tr} defer tr.CloseIdleConnections() r := must(c.Get(s.URL)) must(io.ReadAll(r.Body)) check(r.Body.Close()) tr.CloseIdleConnections() reused := true q := must(http.NewRequest("GET", s.URL, nil)) q = q.WithContext(httptrace.WithClientTrace(q.Context(), &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) { reused = i.Reused }})) r = must(c.Do(q)) defer r.Body.Close() fmt.Println(!reused)}func fixture() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/redirect": http.Redirect(w, r, "/done", http.StatusFound) case "/cookie": http.SetCookie(w, &http.Cookie{Name: "demo", Value: "yes", Path: "/", HttpOnly: true}) case "/echo": c, e := r.Cookie("demo") if e == nil { fmt.Fprint(w, c.Value) } default: fmt.Fprint(w, "hello") } }))}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}