Standard library / net/http
http.Client
Configure request timeout, redirect policy, cookie jar and transport; reuse clients across requests. Expected stdout: '200\n'.
Formal Syntax & Structure
go syntaxgo
type Client struct { Transport RoundTripper
CheckRedirect func(req *Request, via []*Request) error
Jar CookieJar
Timeout time.Duration}Working Example
Example Snippetgo
package main
import ( "fmt" "io" "net/http" "net/http/httptest" "time")
func main() { s := fixture() defer s.Close() c := &http.Client{Timeout: time.Second} r := must(c.Get(s.URL)) defer r.Body.Close() fmt.Println(r.StatusCode)}func fixture() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Demo", "yes") if r.Method == "POST" { b, e := io.ReadAll(io.LimitReader(r.Body, 1025)) check(e) if len(b) > 1024 { w.WriteHeader(413) return } fmt.Fprint(w, string(b)) return } 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) }}