gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/util/http/roundtripper.go (about)

     1  package http
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  
     7  	"gitee.com/liuxuezhan/go-micro-v1.18.0/client/selector"
     8  )
     9  
    10  type roundTripper struct {
    11  	rt   http.RoundTripper
    12  	st   selector.Strategy
    13  	opts Options
    14  }
    15  
    16  func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    17  	s, err := r.opts.Registry.GetService(req.URL.Host)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	next := r.st(s)
    23  
    24  	// rudimentary retry 3 times
    25  	for i := 0; i < 3; i++ {
    26  		n, err := next()
    27  		if err != nil {
    28  			continue
    29  		}
    30  		req.URL.Host = n.Address
    31  		w, err := r.rt.RoundTrip(req)
    32  		if err != nil {
    33  			continue
    34  		}
    35  		return w, nil
    36  	}
    37  
    38  	return nil, errors.New("failed request")
    39  }