github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/http/helper_liveness_checker.go (about) 1 package http 2 3 import ( 4 "context" 5 "reflect" 6 7 "github.com/machinefi/w3bstream/pkg/depends/base/types" 8 "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx" 9 "github.com/machinefi/w3bstream/pkg/depends/kit/kit" 10 "github.com/machinefi/w3bstream/pkg/depends/x/reflectx" 11 ) 12 13 type LivenessChecker interface { 14 LivenessCheck() map[string]string 15 } 16 17 var ( 18 RTypeLivenessChecker = reflect.TypeOf((*LivenessChecker)(nil)).Elem() 19 ) 20 21 func RegisterCheckerBy(vs ...interface{}) { 22 for _, v := range vs { 23 rv := reflectx.Indirect(reflect.ValueOf(v)) 24 rt := rv.Type() 25 26 if register(v) { 27 continue 28 } 29 30 if rt.Kind() != reflect.Struct { 31 continue 32 } 33 34 for i := 0; i < rv.NumField(); i++ { 35 fv := rv.Field(i) 36 ft := rt.Field(i) 37 38 if !ft.IsExported() { 39 continue 40 } 41 register(fv.Interface()) 42 } 43 } 44 } 45 46 func register(v interface{}) bool { 47 if chk, ok := v.(LivenessChecker); ok { 48 if named, ok := v.(types.Named); ok { 49 checkers[named.Name()] = chk 50 } else { 51 checkers[reflect.Indirect(reflect.ValueOf(v)).Type().Name()] = chk 52 } 53 return true 54 } 55 return false 56 } 57 58 func ResetRegistered() { checkers = LivenessCheckers{} } 59 60 type LivenessCheckers map[string]LivenessChecker 61 62 var checkers = LivenessCheckers{} 63 64 func (cs LivenessCheckers) Statuses() map[string]string { 65 m := map[string]string{} 66 67 for name := range cs { 68 if cs[name] != nil { 69 entry := cs[name].LivenessCheck() 70 for key, v := range entry { 71 if key != "" { 72 m[name+"/"+key] = v 73 } else { 74 m[name] = v 75 } 76 } 77 } 78 } 79 80 return m 81 } 82 83 var LivenessRouter = kit.NewRouter(&Liveness{}) 84 85 type Liveness struct{ httpx.MethodGet } 86 87 func (Liveness) Path() string { return "/liveness" } 88 89 func (Liveness) Output(ctx context.Context) (interface{}, error) { 90 return checkers.Statuses(), nil 91 }