Simple JS->DNS Proxy with golang server side
I wanted the ability to resolve DNS addresses in client side Javascript. Unfortunately you can’t do DNS lookups in browser. As a hack I wrote a quick DNS proxy in golang which allows the JS to perform GET requests to a golang server which will lookup and DNS entry and return IP addresses.
The HTML and golang code is below, there’s also a tarball here. You can run the go code with “go run”. If the html file is stored in the same directory you will be able to access it from localhost at http://localhost:8080/web.html.
<html> <head> <meta charset="UTF-8" /> <script> function gethostbyname(hostname) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", "http://localhost:8080/dns?hostname=" + hostname, false); xmlHttp.send(null); return xmlHttp.responseText; } function press() { var hostname = document.getElementById('hostname').value; document.getElementById('comms').innerHTML += hostname + "=" + gethostbyname(hostname) + "<br>"; } </script> </head> <body> ServerIP: <input id="hostname" type="text" /><br> <input type="button" id="lookup" value="lookup" onclick="press()"></input><br><br> <div id='comms'></div> </body> </html>
package main import ( "net/http" "net" "fmt" ) func DNSProxyHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() hostname := r.Form.Get("hostname") fmt.Printf("hostname: %s\n",hostname) addrs, err := net.LookupIP(hostname) var sendbytes string; if err == nil { sendbytes = addrs[0].String() fmt.Printf("sending: %s",sendbytes) } else { fmt.Printf("fail in dnsroxy\n") } fmt.Fprintf(w, "%s",sendbytes); } func main() { http.HandleFunc("/dns" , DNSProxyHandler) http.Handle("/", http.FileServer(http.Dir("."))) err := http.ListenAndServe(":8080", nil) if err != nil { panic("Error: " + err.Error()) } }