github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/cmd/health/main.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"math"
     7  	"net/http"
     8  	"os"
     9  	"strings"
    10  
    11  	"github.com/caos/orbos/internal/helpers"
    12  )
    13  
    14  func main() {
    15  
    16  	listen := flag.String("listen", "", "Proxy health checks at this listen address")
    17  	protocol := flag.String("protocol", "", "HTTP or HTTPS")
    18  	ip := flag.String("ip", "", "Target IP")
    19  	port := flag.Int("port", 0, "Target Port")
    20  	path := flag.String("path", "", "Target Path")
    21  	status := flag.Int("status", 0, "Expected response status")
    22  	proxy := flag.Bool("proxy", false, "Test a proxy protocol using endpoint")
    23  
    24  	flag.Parse()
    25  
    26  	defer func() {
    27  		err := recover()
    28  		if err != nil {
    29  			fmt.Println(err)
    30  			os.Exit(1)
    31  		}
    32  	}()
    33  
    34  	if *port > math.MaxUint16 {
    35  		panic(fmt.Errorf("max port allowed: %d", math.MaxUint16))
    36  	}
    37  
    38  	listenVal := *listen
    39  	if listenVal == "" {
    40  		msg, err := helpers.Check(*protocol, *ip, uint16(*port), *path, *status, *proxy)
    41  		if err != nil {
    42  			panic(err)
    43  		}
    44  		fmt.Printf(msg)
    45  		os.Exit(0)
    46  	}
    47  
    48  	pathStart := strings.Index(listenVal, "/")
    49  	serve := listenVal[0:pathStart]
    50  	servePath := listenVal[pathStart:]
    51  	http.HandleFunc(servePath, func(writer http.ResponseWriter, request *http.Request) {
    52  		msg, err := helpers.Check(*protocol, *ip, uint16(*port), *path, *status, *proxy)
    53  		if err != nil {
    54  			writer.WriteHeader(http.StatusServiceUnavailable)
    55  		}
    56  		writer.Write([]byte(msg))
    57  		request.Body.Close()
    58  	})
    59  	fmt.Printf("Serving healthchecks at %s", listenVal)
    60  	if err := http.ListenAndServe(serve, nil); err != nil {
    61  		panic(err)
    62  	}
    63  }