Standard library / net/http
http.Transport.RoundTrip()
Execute one transaction without following redirects or managing a cookie jar. Close the response body. Expected stdout: '302\n'.
Formal Syntax & Structure
go syntaxgo
func (t *Transport) RoundTrip(req *Request) (*Response, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| req | *Request | HTTP request associated with the operation. |
Return Value
(*Response, error)
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "fmt" "net/http" "net/http/httptest")
func main() { s := fixture() defer s.Close() tr := &http.Transport{} defer tr.CloseIdleConnections() r := must(tr.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) }}