How to use RoundTrip method of httpext Package

Best K6 code snippet using httpext.RoundTrip

transport.go

Source:transport.go Github

copy

Full Screen

...28 "github.com/luckybroman5/http-log-reconstructor/k6/lib"29 "github.com/luckybroman5/http-log-reconstructor/k6/lib/netext"30 "github.com/luckybroman5/http-log-reconstructor/k6/stats"31)32// transport is an implemenation of http.RoundTripper that will measure and emit33// different metrics for each roundtrip34type transport struct {35 state *lib.State36 tags map[string]string37 lastRequest *unfinishedRequest38 lastRequestLock *sync.Mutex39}40// unfinishedRequest stores the request and the raw result returned from the41// underlying http.RoundTripper, but before its body has been read42type unfinishedRequest struct {43 ctx context.Context44 tracer *Tracer45 request *http.Request46 response *http.Response47 err error48}49// finishedRequest is produced once the request has been finalized; it is50// triggered either by a subsequent RoundTrip, or for the last request in the51// chain - by the MakeRequest function manually calling the transport method52// processLastSavedRequest(), after reading the HTTP response body.53type finishedRequest struct {54 *unfinishedRequest55 trail *Trail56 tlsInfo netext.TLSInfo57 errorCode errCode58 errorMsg string59}60var _ http.RoundTripper = &transport{}61// newTransport returns a new http.RoundTripper implementation that wraps around62// the provided state's Transport. It uses a httpext.Tracer to measure all HTTP63// requests made through it and annotates and emits the recorded metric samples64// through the state.Samples channel.65func newTransport(66 state *lib.State,67 tags map[string]string,68) *transport {69 return &transport{70 state: state,71 tags: tags,72 lastRequestLock: new(sync.Mutex),73 }74}75// Helper method to finish the tracer trail, assemble the tag values and emits76// the metric samples for the supplied unfinished request.77func (t *transport) measureAndEmitMetrics(unfReq *unfinishedRequest) *finishedRequest {78 trail := unfReq.tracer.Done()79 tags := map[string]string{}80 for k, v := range t.tags {81 tags[k] = v82 }83 result := &finishedRequest{84 unfinishedRequest: unfReq,85 trail: trail,86 }87 enabledTags := t.state.Options.SystemTags88 if unfReq.err != nil {89 result.errorCode, result.errorMsg = errorCodeForError(unfReq.err)90 if enabledTags.Has(stats.TagError) {91 tags["error"] = result.errorMsg92 }93 if enabledTags.Has(stats.TagErrorCode) {94 tags["error_code"] = strconv.Itoa(int(result.errorCode))95 }96 if enabledTags.Has(stats.TagStatus) {97 tags["status"] = "0"98 }99 } else {100 if enabledTags.Has(stats.TagURL) {101 u := URL{u: unfReq.request.URL, URL: unfReq.request.URL.String()}102 tags["url"] = u.Clean()103 }104 if enabledTags.Has(stats.TagStatus) {105 tags["status"] = strconv.Itoa(unfReq.response.StatusCode)106 }107 if unfReq.response.StatusCode >= 400 {108 if enabledTags.Has(stats.TagErrorCode) {109 result.errorCode = errCode(1000 + unfReq.response.StatusCode)110 tags["error_code"] = strconv.Itoa(int(result.errorCode))111 }112 }113 if enabledTags.Has(stats.TagProto) {114 tags["proto"] = unfReq.response.Proto115 }116 if unfReq.response.TLS != nil {117 tlsInfo, oscp := netext.ParseTLSConnState(unfReq.response.TLS)118 if enabledTags.Has(stats.TagTLSVersion) {119 tags["tls_version"] = tlsInfo.Version120 }121 if enabledTags.Has(stats.TagOCSPStatus) {122 tags["ocsp_status"] = oscp.Status123 }124 result.tlsInfo = tlsInfo125 }126 }127 if enabledTags.Has(stats.TagIP) && trail.ConnRemoteAddr != nil {128 if ip, _, err := net.SplitHostPort(trail.ConnRemoteAddr.String()); err == nil {129 tags["ip"] = ip130 }131 }132 trail.SaveSamples(stats.IntoSampleTags(&tags))133 stats.PushIfNotCancelled(unfReq.ctx, t.state.Samples, trail)134 return result135}136func (t *transport) saveCurrentRequest(currentRequest *unfinishedRequest) {137 t.lastRequestLock.Lock()138 unprocessedRequest := t.lastRequest139 t.lastRequest = currentRequest140 t.lastRequestLock.Unlock()141 if unprocessedRequest != nil {142 // This shouldn't happen, since we have one transport per request, but just in case...143 t.state.Logger.Warnf("TracerTransport: unexpected unprocessed request for %s", unprocessedRequest.request.URL)144 t.measureAndEmitMetrics(unprocessedRequest)145 }146}147func (t *transport) processLastSavedRequest(lastErr error) *finishedRequest {148 t.lastRequestLock.Lock()149 unprocessedRequest := t.lastRequest150 t.lastRequest = nil151 t.lastRequestLock.Unlock()152 if unprocessedRequest != nil {153 // We don't want to overwrite any previous errors, but if there were154 // none and we (i.e. the MakeRequest() function) have one, save it155 // before we emit the metrics.156 if unprocessedRequest.err == nil && lastErr != nil {157 unprocessedRequest.err = lastErr158 }159 return t.measureAndEmitMetrics(unprocessedRequest)160 }161 return nil162}163// RoundTrip is the implementation of http.RoundTripper164func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {165 t.processLastSavedRequest(nil)166 ctx := req.Context()167 tracer := &Tracer{}168 reqWithTracer := req.WithContext(httptrace.WithClientTrace(ctx, tracer.Trace()))169 resp, err := t.state.Transport.RoundTrip(reqWithTracer)170 t.saveCurrentRequest(&unfinishedRequest{171 ctx: ctx,172 tracer: tracer,173 request: req,174 response: resp,175 err: err,176 })177 return resp, err178}...

Full Screen

Full Screen

lazy_rate_limiter.go

Source:lazy_rate_limiter.go Github

copy

Full Screen

...16 "net/http"17 "time"18 "github.com/jadefox10200/backoff"19)20// A LazyRateLimiter implements rate limiting for an http.RoundTripper object.21// Rate limiting start when the server responds with 429 Too Many Requests.22type LazyRateLimiter struct {23 transport http.RoundTripper24 backoffPolicy backoff.Policy25}26// NewLazyRateLimiter returns a new LazyRateLimiter given a transport and27// backoff policy. The transport will use http.DefaultTransport when nil. The28// backoff policy will use backoff.Default when nil.29func NewLazyRateLimiter(transport http.RoundTripper, backoffPolicy backoff.Policy) LazyRateLimiter {30 // Use http.DefaultTransport when nil.31 if transport == nil {32 transport = http.DefaultTransport33 }34 // Use backoff.Default when nil.35 if backoffPolicy == nil {36 backoffPolicy = backoff.Default()37 }38 return LazyRateLimiter{transport, backoffPolicy}39}40// RoundTrip implemented the http.RoundTripper interface.41func (lrl LazyRateLimiter) RoundTrip(req *http.Request) (*http.Response, error) {42 resp, err := lrl.transport.RoundTrip(req)43 // Decrease the backoff policy delay if the server does not respond with 42944 // Too Many Requests.45 if resp.StatusCode != http.StatusTooManyRequests {46 lrl.backoffPolicy.Decrease()47 } else {48 // Repeat until the server does not respond with 429 Too Many Requests.49 for resp.StatusCode == http.StatusTooManyRequests {50 if err := resp.Body.Close(); err != nil {51 return nil, err52 }53 // Rate limit based on the Retry-After header or otherwise use the54 // backoff policy.55 d, err := ParseRetryAfter(resp.Header.Get("Retry-After"))56 if err != nil {57 d = lrl.backoffPolicy.Increase()58 }59 time.Sleep(d)60 resp, err = lrl.transport.RoundTrip(req)61 if err != nil {62 return nil, err63 }64 }65 }66 return resp, err67}...

Full Screen

Full Screen

round_tripper_func.go

Source:round_tripper_func.go Github

copy

Full Screen

...12// See the License for the specific language governing permissions and13// limitations under the License.14package httpext15import "net/http"16// A RoundTripperFunc is a function used as the RoundTrip method for the17// http.RoundTripper interface.18type RoundTripperFunc func(req *http.Request) (*http.Response, error)19// RoundTrip implements the http.RoundTripper interface.20func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {21 return f(req)22}23// WithTransportFunc returns a copy of a client that uses a given24// RoundTripperFunc as the transport. The client will default to25// http.DefaultClient when nil.26func WithTransportFunc(c *http.Client, f RoundTripperFunc) *http.Client {27 if c == nil {28 c = http.DefaultClient29 }30 clientWithTransport := *c31 clientWithTransport.Transport = f32 return &clientWithTransport33}...

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error: ", err)5 }6 client := http.Client{}7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println("Error: ", err)10 }11 defer resp.Body.Close()12 fmt.Println("Response status: ", resp.Status)13 dump, err := httputil.DumpResponse(resp, true)14 if err != nil {15 fmt.Println("Error: ", err)16 }17 fmt.Println(string(dump))18}19Content-Type: text/html; charset=ISO-8859-120Set-Cookie: 1P_JAR=2020-02-24-14; expires=Wed, 25-Mar-2020 14:46:57 GMT; path=/; domain=.google.com

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 rec := httptest.NewRecorder()7 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {8 fmt.Fprintf(w, "Hello World")9 })10 httpext := httputil.NewServerConn(rec, nil)

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1func main() {2 if err != nil {3 log.Fatal(err)4 }5 client := &http.Client{}6 resp, err := client.Do(req)7 if err != nil {8 log.Fatal(err)9 }10 defer resp.Body.Close()11 body, err := ioutil.ReadAll(resp.Body)12 if err != nil {13 log.Fatal(err)14 }15 fmt.Println(string(body))16}

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req, _ := http.NewRequest("GET", u.String(), nil)4 rt := &http.Transport{}5 h := &httpext{rt}6 client := &http.Client{Transport: h}7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println(err)10 }11 b, _ := httputil.DumpResponse(resp, true)12 fmt.Println(string(b))13}14import (15func main() {16 req, _ := http.NewRequest("GET", u.String(), nil)17 rt := &http.Transport{}18 h := &httpext{rt}19 client := &http.Client{Transport: h}20 resp, err := client.Do(req)21 if err != nil {22 fmt.Println(err)23 }24 b, _ := httputil.DumpResponse(resp, true)25 fmt.Println(string(b))26}27import (28func main() {29 req, _ := http.NewRequest("GET", u.String(), nil

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 resp, _ := client.Do(req)5 fmt.Println(resp)6 dump, _ := httputil.DumpResponse(resp, true)7 fmt.Println(string(dump))8}9Content-Type: text/html; charset=ISO-8859-110X-XSS-Protection: 1; mode=block11Set-Cookie: 1P_JAR=2018-04-15-08; expires=Mon, 15-May-2018 08:30:22 GMT; path=/; domain=.google.com12Set-Cookie: NID=130=J1p6mBd6F0w6q3CZt1kZt9i9b8Wl2QcQbRfR5d5j5l5w7VZfzrZB7g2o8hWf7VZBn0u6Jxg0K8Ww0Z3q3p1z9v9m5B0z5y2Q5y5m5m5d5f5w; expires=Tue, 14-Oct-2018 08:30:22 GMT; path=/; domain=.google.com; HttpOnly

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 client := &http.Client{}7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println(err)10 }11 defer resp.Body.Close()12 body, err := ioutil.ReadAll(resp.Body)13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println(string(body))17}18import (19func main() {20 if err != nil {21 fmt.Println(err)22 }23 client := &http.Client{}24 resp, err := client.Do(req)25 if err != nil {26 fmt.Println(err)27 }28 defer resp.Body.Close()29 body, err := ioutil.ReadAll(resp.Body)30 if err != nil {31 fmt.Println(err)32 }33 fmt.Println(string(body))34}35import (36func main() {37 if err != nil {38 fmt.Println(err)39 }40 client := &http.Client{}41 resp, err := client.Do(req)42 if err != nil {43 fmt.Println(err)44 }45 defer resp.Body.Close()46 body, err := ioutil.ReadAll(resp.Body)47 if err != nil {48 fmt.Println(err)49 }50 fmt.Println(string(body))51}52import (53func main() {

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 client := http.Client{}7 resp, err := client.Do(req)8 if err != nil {9 panic(err)10 }11 body, err := ioutil.ReadAll(resp.Body)12 if err != nil {13 panic(err)14 }15 fmt.Println(string(body))16}17{"url":"/get","headers":{"Accept-Encoding":["gzip"],"Connection":["close"],"User-Agent":["Go-http-client/1.1"]}}18import (19func main() {20 if err != nil {21 panic(err)22 }23 resp, err := http.DefaultClient.Do(req)24 if err != nil {25 panic(err)26 }27 body, err := ioutil.ReadAll(resp.Body)28 if err != nil {29 panic(err)30 }31 fmt.Println(string(body))32}33{"url":"/get","headers":{"Accept-Encoding":["gzip"],"Connection":["close"],"User-Agent":["Go-http-client/1.1"]}}34Example 3: How to use http.Get()?35import (36func main() {37 if err != nil {38 panic(err)39 }40 body, err := ioutil.ReadAll(resp.Body)41 if err != nil {42 panic(err)43 }44 fmt.Println(string(body))45}

Full Screen

Full Screen

RoundTrip

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client {4 }5 req, err := http.NewRequest(method, url, nil)6 if err != nil {7 fmt.Println(err)8 }9 res, err := client.Do(req)10 defer res.Body.Close()11 body, err := ioutil.ReadAll(res.Body)12 fmt.Println(string(body))13}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful