Last active
October 16, 2019 19:07
-
-
Save silveiralexf/2797fb68f9bf51eb7800b8ddf5b74d57 to your computer and use it in GitHub Desktop.
Command line utility to display app status in a given port -- useful for example for signaling successful start of an application for other pods waiting with initContainers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
) | |
type App struct { | |
Name string | |
Port int | |
Status int | |
} | |
const ( | |
errMsg = (`ERROR: You did not specify a valid command or failed to pass the proper options. Exiting! | |
Use "-help" or "-h" for usage instructions. | |
`) | |
helpMsg = (`This utility will expose the status of an application in a given HTTP port. | |
making easier to confirm the status from outside. | |
Usage: | |
showstat -n [ <app_name> ] -p <port_number> -s <status_code> | |
Examples: | |
$ showstat -n myappname -p 9988 -s 0 | |
`) | |
) | |
var ( | |
name = flag.String("n", "", "Name of application for which the status will be shown.") | |
port = flag.Int("p", 9988, "Port number where the application status will be displayed -- default is 9988") | |
status = flag.Int("s", 0, "Status of the application: 0 = running / 1 = not running -- default is 0") | |
) | |
func main() { | |
flag.Usage = func() { | |
flagSet := flag.CommandLine | |
fmt.Println(helpMsg) | |
order := []string{"n", "p", "s"} | |
for _, name := range order { | |
flag := flagSet.Lookup(name) | |
fmt.Printf(" -%s ", flag.Name) | |
fmt.Printf(" %s\n", flag.Usage) | |
} | |
} | |
flag.Parse() | |
if *name != "" { | |
strPort := fmt.Sprintf(":%v", (*port)) | |
fmt.Printf("INFO: '%s' is listening on port %v with status %v", *name, *port, *status) | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(strPort, nil) | |
} else { | |
fmt.Println(errMsg) | |
os.Exit(2) | |
} | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
app := &App{Name: *name, Port: *port, Status: *status} | |
resp, err := json.Marshal(app) | |
if err != nil { | |
log.Fatal("ERROR:", err) | |
} | |
fmt.Fprintf(w, string(resp)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment