From 507b16fbd018fdb8a35e9a8c93c65cd579d7a243 Mon Sep 17 00:00:00 2001 From: cynic Date: Thu, 8 Aug 2024 14:54:19 +0000 Subject: [PATCH] add ip=true optional parameter --- cmd/whoami/main.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/cmd/whoami/main.go b/cmd/whoami/main.go index 2eb5fbf..86d3ff2 100644 --- a/cmd/whoami/main.go +++ b/cmd/whoami/main.go @@ -6,6 +6,7 @@ import ( "encoding/base32" "strings" "flag" + "log" ) // define tld @@ -14,12 +15,17 @@ var tld = flag.String("tld", "mesh.cat", "The top level domain for our network") // domainFromIP derives a meshname subdomain for the authoritative DNS server address func domainFromIP(target net.IP) string { host := strings.ToLower(base32.StdEncoding.EncodeToString(target)[0:26]) - domain := strings.Join([]string{host, ".", *tld, "\n"}, "") + domain := host + "." + *tld return domain } // handle HTTP requests func handler(w http.ResponseWriter, r *http.Request) { + // parse query parameters + params := r.URL.Query() + ipParam := params.Get("ip") + // check if the "ip" query parameter is set to "true" + showIP := ipParam == "true" // get client's ip address ip, port, err := net.SplitHostPort(r.RemoteAddr) _, _ = port, err @@ -31,7 +37,13 @@ func handler(w http.ResponseWriter, r *http.Request) { parsedIP := net.ParseIP(ip) // return domain for IPv6 only if parsedIP.To4() == nil { - w.Write([]byte(domainFromIP(parsedIP))) + if (showIP) { + w.Write([]byte(ip + "\n")) + } else { + w.Write([]byte(domainFromIP(parsedIP) + "\n")) + } + log.Println(showIP) + log.Println(ip) } else { // set the response status code to 422 w.WriteHeader(http.StatusUnprocessableEntity) @@ -49,7 +61,7 @@ func main() { // parse the command-line arguments flag.Parse() // construct listening address - listenAddr := strings.Join([]string{*address, ":", *port}, "") + listenAddr := *address + ":" + *port print("Listening on address: ", listenAddr, "\n") // start server http.ListenAndServe(listenAddr, nil)