Standard library / net/http

http.Transport

Reusable concurrency-safe HTTP transport with connection pooling, proxy and timeout options. Configure before use; avoid modifying it in flight. Expected stdout: 'hello\n'.

Formal Syntax & Structure

go syntaxgo
type Transport struct {
  Proxy func(*Request) (*url.URL, error)
  OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error
  DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
  Dial func(network, addr string) (net.Conn, error)
  DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
  DialTLS func(network, addr string) (net.Conn, error)
  TLSClientConfig *tls.Config
  TLSHandshakeTimeout time.Duration
  DisableKeepAlives bool
  DisableCompression bool
  MaxIdleConns int
  MaxIdleConnsPerHost int
  MaxConnsPerHost int
  IdleConnTimeout time.Duration
  ResponseHeaderTimeout time.Duration
  ExpectContinueTimeout time.Duration
  TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
  ProxyConnectHeader Header
  GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error)
  MaxResponseHeaderBytes int64
  WriteBufferSize int
  ReadBufferSize int
  ForceAttemptHTTP2 bool}

Working Example

Example Snippetgo
package main
import (  "fmt"  "io"  "net/http"  "net/http/httptest"  "time")
func main() {  s := fixture()  defer s.Close()  tr := &http.Transport{MaxIdleConns: 10, ResponseHeaderTimeout: time.Second}  defer tr.CloseIdleConnections()  c := &http.Client{Transport: tr, Timeout: time.Second}  r := must(c.Get(s.URL))  defer r.Body.Close()  fmt.Println(string(must(io.ReadAll(r.Body))))}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)  }}
Go Reference