From c3a54a1b85963500a33dc2e649f6a12daafdae78 Mon Sep 17 00:00:00 2001 From: Buddy Sandidge Date: Fri, 11 Nov 2016 18:58:33 -0800 Subject: [PATCH] Add proof of concept WebApp with basic functionality MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO: • Add arguments to app for port and address • Add x-forwarded-for header support for use behind proxies • Be able to give response in text, json or html --- .gitignore | 1 + what-is-my-ip.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 .gitignore create mode 100644 what-is-my-ip.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d149a94 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +what-is-my-ip diff --git a/what-is-my-ip.go b/what-is-my-ip.go new file mode 100644 index 0000000..b01a788 --- /dev/null +++ b/what-is-my-ip.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "io" + "log" + "net" + "net/http" +) + +func main() { + http.HandleFunc("/", getIP) + fmt.Println("listening on port 3000") + http.ListenAndServe(":3000", 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) +}