Skip to content

Instantly share code, notes, and snippets.

@funzoneq
Created July 22, 2016 14:12
Show Gist options
  • Save funzoneq/4c98e20b53c8996fc62ae7de82136434 to your computer and use it in GitHub Desktop.
Save funzoneq/4c98e20b53c8996fc62ae7de82136434 to your computer and use it in GitHub Desktop.
nslookup go api endpoint
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"github.com/miekg/dns"
"net/http"
"encoding/json"
"log"
)
type Status struct {
Name string
Free string
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Lookup(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
target := ps.ByName("name")
server := "8.8.8.8"
free := "false"
c := dns.Client{}
m := dns.Msg{}
m.SetQuestion(target+".", dns.TypeNS)
res, _, err := c.Exchange(&m, server+":53")
if err != nil {
log.Printf("%s", err)
free = "unknown"
} else {
// log.Printf("Took %v", t)
if len(res.Answer) == 0 {
free = "true"
log.Printf("No results for %s", target)
}
/* for _, ans := range res.Answer {
NSrecord := ans.(*dns.NS)
log.Printf("%s", NSrecord.Ns)
} */
}
status := Status{target, free}
js, err := json.Marshal(status)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/free/:name", Lookup)
log.Fatal(http.ListenAndServe(":80", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment