github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/http/helper_client_endpoint.go (about) 1 package http 2 3 import ( 4 "context" 5 "net/http" 6 "time" 7 8 "github.com/machinefi/w3bstream/pkg/depends/base/types" 9 "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/client" 10 "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/client/roundtrippers" 11 "github.com/machinefi/w3bstream/pkg/depends/kit/kit" 12 "github.com/machinefi/w3bstream/pkg/depends/kit/statusx" 13 ) 14 15 type ClientEndpoint struct { 16 Endpoint types.Endpoint `env:""` 17 Timeout time.Duration 18 19 client.Client `env:"-"` 20 } 21 22 func (c *ClientEndpoint) Do(ctx context.Context, req interface{}, metas ...kit.Metadata) kit.Result { 23 return c.Client.Do(ctx, req, metas...) 24 } 25 26 func (c *ClientEndpoint) LivenessCheck() map[string]string { 27 s := map[string]string{} 28 s[c.Endpoint.Host()] = "ok" 29 30 _, err := c.Do(context.Background(), NewRequest(http.MethodGet, "/liveness")).Into(&s) 31 if err != nil { 32 if statusx.FromErr(err).StatusCode() != http.StatusNotFound { 33 s[c.Endpoint.Host()] = err.Error() 34 } 35 } 36 return s 37 } 38 39 func (c *ClientEndpoint) SetDefault() { 40 c.Client.SetDefault() 41 c.Client.Transports = []client.HttpTransport{ 42 roundtrippers.NewLogRoundTripper(), 43 } 44 } 45 46 func (c *ClientEndpoint) Init() { 47 if c.Endpoint.Scheme != "" { 48 c.Client.Protocol = c.Endpoint.Scheme 49 } 50 if c.Endpoint.Hostname != "" { 51 c.Client.Host = c.Endpoint.Hostname 52 } 53 if c.Endpoint.Port != 0 { 54 c.Client.Port = c.Endpoint.Port 55 } 56 if c.Timeout != 0 { 57 c.Client.Timeout = c.Timeout 58 } 59 } 60 61 func NewRequest(method string, path string) *request { 62 return &request{method: method, path: path} 63 } 64 65 type request struct { 66 method string 67 path string 68 } 69 70 func (req *request) Method() string { return req.method } 71 72 func (req *request) Path() string { return req.path }