github.com/verrazzano/verrazzano-monitoring-operator@v0.0.30/pkg/vmo/http.go (about)

     1  // Copyright (C) 2020, 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package vmo
     5  
     6  import (
     7  	"net/http"
     8  	"path"
     9  	"time"
    10  
    11  	"k8s.io/apimachinery/pkg/util/wait"
    12  )
    13  
    14  // StartHTTPServer runs an embedded HTTP server for any VMO handlers as a "resilient" goroutine meaning it runs in
    15  // the background and will be restarted if it dies.
    16  func StartHTTPServer(controller *Controller, certdir string, port string) {
    17  	setupHandlers(controller)
    18  	go wait.Until(func() {
    19  		server := &http.Server{
    20  			Addr:              ":" + port,
    21  			ReadHeaderTimeout: 3 * time.Second,
    22  		}
    23  		controller.log.Oncef("Starting HTTP server")
    24  		err := server.ListenAndServeTLS(path.Join(certdir, "tls.crt"), path.Join(certdir, "tls.key"))
    25  		if err != nil {
    26  			controller.log.Errorf("Failed to start HTTP server for VMI: %v", err)
    27  		}
    28  	}, time.Second*3, wait.NeverStop)
    29  }
    30  
    31  func setupHandlers(controller *Controller) {
    32  	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
    33  		if controller.IsHealthy() {
    34  			w.WriteHeader(http.StatusOK)
    35  			if _, err := w.Write([]byte("ok")); err != nil {
    36  				controller.log.Errorf("Failed writing healthcheck response: %v", err)
    37  			}
    38  		} else {
    39  			w.WriteHeader(http.StatusInternalServerError)
    40  		}
    41  	})
    42  }