2019-05-30 23:52:10 +01:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/router"
|
|
|
|
"github.com/micro/go-micro/v3/selector"
|
2019-05-30 23:52:10 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type roundTripper struct {
|
|
|
|
rt http.RoundTripper
|
2020-07-01 17:06:59 +01:00
|
|
|
st selector.Selector
|
2019-05-30 23:52:10 +01:00
|
|
|
opts Options
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
2020-07-01 17:06:59 +01:00
|
|
|
routes, err := r.opts.Router.Lookup(router.QueryService(req.URL.Host))
|
2019-05-30 23:52:10 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// rudimentary retry 3 times
|
|
|
|
for i := 0; i < 3; i++ {
|
2020-07-01 17:06:59 +01:00
|
|
|
route, err := r.st.Select(routes)
|
2019-05-30 23:52:10 +01:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2020-07-01 17:06:59 +01:00
|
|
|
|
|
|
|
req.URL.Host = route.Address
|
2019-05-30 23:52:10 +01:00
|
|
|
w, err := r.rt.RoundTrip(req)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2020-07-01 17:06:59 +01:00
|
|
|
|
2019-05-30 23:52:10 +01:00
|
|
|
return w, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("failed request")
|
|
|
|
}
|