You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
what-is-my-ip/what-is-my-ip.go

55 lines
1.1 KiB
Go

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.1.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",
},
}
app.Run(os.Args)
}
func action(c *cli.Context) error {
http.HandleFunc("/", getIP)
address := c.String("address")
fmt.Printf("listening on %s\n", address)
return http.ListenAndServe(address, 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)
}