2023-03-27 10:14:05 +00:00
|
|
|
package ingress
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
corev1 "k8s.io/api/core/v1"
|
2023-04-03 08:06:06 +00:00
|
|
|
netv1 "k8s.io/api/networking/v1"
|
2023-03-27 10:14:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type marshaler interface {
|
|
|
|
Marshal() ([]byte, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type unmarshaler interface {
|
2023-11-17 00:50:06 +00:00
|
|
|
Unmarshal(data []byte) error
|
2023-03-27 10:14:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type LoadBalancerIngress interface {
|
2023-06-20 08:26:05 +00:00
|
|
|
corev1.LoadBalancerIngress | netv1.IngressLoadBalancerIngress
|
2023-03-27 10:14:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// convertSlice converts slice of LoadBalancerIngress to slice of LoadBalancerIngress.
|
|
|
|
// O (Bar), I (Foo) => []Bar.
|
|
|
|
func convertSlice[O LoadBalancerIngress, I LoadBalancerIngress](loadBalancerIngresses []I) ([]O, error) {
|
|
|
|
var results []O
|
|
|
|
|
|
|
|
for _, loadBalancerIngress := range loadBalancerIngresses {
|
|
|
|
mar, ok := any(&loadBalancerIngress).(marshaler)
|
|
|
|
if !ok {
|
|
|
|
// All the pointer of types related to the interface LoadBalancerIngress are compatible with the interface marshaler.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
um, err := convert[O](mar)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
v, ok := any(*um).(O)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
results = append(results, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
return results, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// convert must only be used with unmarshaler and marshaler compatible types.
|
|
|
|
func convert[T any](input marshaler) (*T, error) {
|
|
|
|
data, err := input.Marshal()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var output T
|
|
|
|
um, ok := any(&output).(unmarshaler)
|
|
|
|
if !ok {
|
|
|
|
return nil, errors.New("the output type doesn't implement unmarshaler interface")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = um.Unmarshal(data)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &output, nil
|
|
|
|
}
|