package main import ( "fmt" "io" "log" "net" "net/http" "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "what-is-my-ip" app.Version = "0.2.0" app.Usage = "Webapp that gives the IP address for incoming requests" app.Action = action app.Flags = []cli.Flag{ cli.StringFlag{ Name: "address, a", Value: ":3000", EnvVar: "WHAT_IS_MY_IP_ADDRESS", Usage: "Address and port to bind to", }, cli.StringFlag{ Name: "certificate, c", Value: "cert.pem", EnvVar: "WHAT_IS_MY_IP_CERTIFICATE", Usage: "path to certificate file for https server", }, cli.StringFlag{ Name: "key, k", Value: "key.pem", EnvVar: "WHAT_IS_MY_IP_KEY", Usage: "path to key file for https server", }, } app.Run(os.Args) } func action(c *cli.Context) error { http.HandleFunc("/", getIP) address := c.String("address") certificate := c.String("certificate") key := c.String("key") fmt.Printf("listening on %s\n", address) return http.ListenAndServeTLS(address, certificate, key, nil) } func getIP(w http.ResponseWriter, req *http.Request) { ip, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { handleError(w, err, "Could not get IP address from request") return } io.WriteString(w, ip+"\n") log.Printf("Give response IP %s\n", ip) } func handleError(resp http.ResponseWriter, err error, message string) { resp.WriteHeader(http.StatusBadRequest) io.WriteString(resp, message) log.Printf("Error handling request: %s (%s)", message, err) }