Standard library / net/http
http.RoundTripper
Concurrency-safe single-transaction interface; must return a response rather than a status-code error when HTTP succeeds. Client handles higher-level redirects and cookies. Expected stdout: '302\n'.
Formal Syntax & Structure
go syntaxgo
type RoundTripper interface { RoundTrip(*Request) (*Response, error)}Working Example
Example Snippetgo
package main
import ( "fmt" "net/http" "net/http/httptest")
func main() { s := fixture() defer s.Close() var rt http.RoundTripper = &http.Transport{} defer rt.(*http.Transport).CloseIdleConnections() r := must(rt.RoundTrip(must(http.NewRequest("GET", s.URL+"/redirect", nil)))) defer r.Body.Close() fmt.Println(r.StatusCode)}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) }}