github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/kubernetes/cmd/health/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "net/http" 7 "os" 8 9 "github.com/micro/cli/v2" 10 "github.com/micro/go-micro/v2/client" 11 gcli "github.com/micro/go-micro/v2/client/grpc" 12 "github.com/micro/go-micro/v2/config/cmd" 13 proto "github.com/micro/go-micro/v2/debug/service/proto" 14 "github.com/micro/go-micro/v2/util/log" 15 _ "github.com/micro/go-plugins/registry/kubernetes/v2" 16 ) 17 18 func init() { 19 os.Setenv("MICRO_REGISTRY", "kubernetes") 20 client.DefaultClient = gcli.NewClient() 21 } 22 23 var ( 24 healthAddress = "127.0.0.1:8080" 25 serverAddress string 26 serverName string 27 ) 28 29 func main() { 30 app := cmd.App() 31 app.Flags = append(app.Flags, &cli.StringFlag{ 32 Name: "health_address", 33 EnvVars: []string{"MICRO_HEALTH_ADDRESS"}, 34 Usage: "Address for the health checker. 127.0.0.1:8080", 35 Value: "127.0.0.1:8080", 36 Destination: &healthAddress, 37 }) 38 39 app.Action = func(c *cli.Context) error { 40 serverName = c.String("server_name") 41 serverAddress = c.String("server_address") 42 43 if addr := c.String("health_address"); len(addr) > 0 { 44 healthAddress = addr 45 } 46 47 if len(healthAddress) == 0 { 48 log.Fatal("health address not set") 49 } 50 if len(serverName) == 0 { 51 log.Fatal("server name not set") 52 } 53 if len(serverAddress) == 0 { 54 log.Fatal("server address not set") 55 } 56 return nil 57 } 58 59 cmd.Init() 60 61 http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { 62 req := client.NewRequest(serverName, "Debug.Health", &proto.HealthRequest{}) 63 rsp := &proto.HealthResponse{} 64 65 err := client.Call(context.TODO(), req, rsp, client.WithAddress(serverAddress)) 66 if err != nil || rsp.Status != "ok" { 67 w.WriteHeader(http.StatusInternalServerError) 68 fmt.Fprint(w, "NOT_HEALTHY") 69 return 70 } 71 w.WriteHeader(http.StatusOK) 72 fmt.Fprint(w, "OK") 73 }) 74 75 if err := http.ListenAndServe(healthAddress, nil); err != nil { 76 log.Fatal(err) 77 } 78 }