Skip to content

Instantly share code, notes, and snippets.

@silveiralexf
Last active October 16, 2019 19:07
Show Gist options
  • Save silveiralexf/2797fb68f9bf51eb7800b8ddf5b74d57 to your computer and use it in GitHub Desktop.
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
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