github.com/qsunny/k8s@v0.0.0-20220101153623-e6dca256d5bf/examples-master/cassandra/go/main.go (about)

     1  package main
     2  
     3  // #include <stdio.h>
     4  // #include <stdlib.h>
     5  import "C"
     6  
     7  import (
     8  	"context"
     9  	"encoding/json"
    10  	"log"
    11  	"strings"
    12  	"unicode"
    13  	"unsafe"
    14  
    15  	"github.com/ericchiang/k8s"
    16  	corev1 "github.com/ericchiang/k8s/apis/core/v1"
    17  )
    18  
    19  type endpoints struct {
    20  	IPs []string `json:"ips"`
    21  }
    22  
    23  // GetEndpoints searches the endpoints of a service returning a list of IP addresses.
    24  //export GetEndpoints
    25  func GetEndpoints(namespace, service, defSeeds *C.char) *C.char {
    26  	ns := C.GoString(namespace)
    27  	svc := C.GoString(service)
    28  	seeds := C.GoString(defSeeds)
    29  
    30  	s := strings.Map(func(r rune) rune {
    31  		if unicode.IsSpace(r) {
    32  			return -1
    33  		}
    34  		return r
    35  	}, seeds)
    36  
    37  	nseeds := strings.Split(s, ",")
    38  	client, err := k8s.NewInClusterClient()
    39  	if err != nil {
    40  		log.Printf("unexpected error opening a connection against API server: %v\n", err)
    41  		log.Printf("returning default seeds: %v\n", nseeds)
    42  		return buildEndpoints(nseeds)
    43  	}
    44  
    45  	ips := make([]string, 0)
    46  
    47  	var endpoints corev1.Endpoints
    48  	err = client.Get(context.Background(), ns, svc, &endpoints)
    49  	if err != nil {
    50  		log.Printf("unexpected error obtaining information about service endpoints: %v\n", err)
    51  		log.Printf("returning default seeds: %v\n", nseeds)
    52  		return buildEndpoints(nseeds)
    53  	}
    54  
    55  	for _, endpoint := range endpoints.Subsets {
    56  		for _, address := range endpoint.Addresses {
    57  			ips = append(ips, *address.Ip)
    58  		}
    59  	}
    60  
    61  	if len(ips) == 0 {
    62  		return buildEndpoints(nseeds)
    63  	}
    64  
    65  	return buildEndpoints(ips)
    66  }
    67  
    68  func buildEndpoints(ips []string) *C.char {
    69  	b, err := json.Marshal(&endpoints{ips})
    70  	if err != nil {
    71  		log.Printf("unexpected error serializing JSON response: %v\n", err)
    72  		rc := C.CString(`{"ips":[]}`)
    73  		defer C.free(unsafe.Pointer(rc))
    74  		return rc
    75  	}
    76  
    77  	rc := C.CString(string(b))
    78  	defer C.free(unsafe.Pointer(rc))
    79  	return rc
    80  }
    81  
    82  func main() {}