net/http Flashcards
(14 cards)
how is json encoded in the body of an http response?
a stream of bytes
how to decode json into a string?
var storage string
decoder := json.NewDecoder(res.Body)
if err := decoder.Decode(&storage); err != nil { return err, “” }
why and how should you explicity close a response body?
defer res.Body.Close()– to avoid memory issues. That said, net/http will handle tearing down the Transport layer connection for you.
how does http.Get work under the hood?
it uses an http.DefaultClient
when would you prefer a Client over using http to make requests?
when you need control over redirect policies, or to change a header:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get(“http://example.com”)
// …
req, err := http.NewRequest(“GET”, “http://example.com”, nil)
// …
req.Header.Add(“If-None-Match”, W/"wyzzy"
)
resp, err := client.Do(req)
where can you configure connection settings (like proxies, TLS, keepalives, compression, etc)?
http.Transport
http.Transport.Proxy
Proxy specifies a function to return a proxy for a given
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
//
// The proxy type is determined by the URL scheme. “http”,
// “https”, “socks5”, and “socks5h” are supported. If the scheme is empty,
// “http” is assumed.
// “socks5” is treated the same as “socks5h”.
//
// If the proxy URL contains a userinfo subcomponent,
// the proxy request will pass the username and password
// in a Proxy-Authorization header.
//
// If Proxy is nil or returns a nil *URL, no proxy is used.
http.Transport.OnProxyConnectResponse
OPCR is called when the Transport gets an HTTP response from a proxy to CONNECT. It’s called before 200 OK is checked. If it returns an error, the request fails with that error
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
TCP connection. If it’s nil then package net is used. Runs concurrently with calls to RT. a RT call that starts a dial may reuse a previous connectoin if the earlier connection idles out before the later DC completes (connection reuse) (how tf does that work)
When should you use Dial instead of DialContext?
trick question– the Dial function is deprecated
what’s a good alternative to the httptrace package?
otel is typically used for larger apps but httptrace is still useful for troubleshooting.
tell me the top 3 things to know aobut func (c *Client) Do(req Request) (Response, error)
- non-2xx status codes won’t return errors
- If body isn’t both read to EOF AND closed, RTer may not be able to reuse connections for keepalives
- 301-303 -> GET w no body; 307, 308 -> original http method and body, if req.GetBody is defined. NewReq auto-sets GB “for common standard library body types”