Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Go web API for TLD checking
package main
import (
"fmt"
"net/http"
"os"
"time"
"io/ioutil"
"encoding/json"
"strings"
)
func check(tldsChannel chan []string) []string {
url := "https://data.iana.org/TLD/tlds-alpha-by-domain.txt"
res, err := http.Get(url)
perror(err)
body, err := ioutil.ReadAll(res.Body)
perror(err)
tlds := strings.Split(string(body), "\n")
tlds = tlds[1:len(tlds)-1]
tldsChannel <- lowercaseSlice(tlds)
return tlds
}
func checker(tldsChannel chan []string) {
for {
select {
case <-time.After(6 * time.Hour):
check(tldsChannel)
}
}
}
func manager(tldsChannel chan []string) {
curr_stuff := check(tldsChannel)
go checker(tldsChannel)
for {
select {
case new_stuff := <-tldsChannel:
curr_stuff = new_stuff
tldsChannel <- curr_stuff
default:
tldsChannel <- curr_stuff
}
}
}
func main() {
tldsChannel := make(chan []string)
go manager(tldsChannel)
http.HandleFunc("/all", func(res http.ResponseWriter, req *http.Request) {
jsonResponse, err := json.Marshal(<-tldsChannel)
perror(err)
fmt.Fprintln(res, string(jsonResponse))
})
http.HandleFunc("/check", func(res http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
v := q.Get("tld")
if (stringInSlice(v,<-tldsChannel)) {
fmt.Fprintln(res, "true")
} else {
fmt.Fprintln(res, "false")
}
})
err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
perror(err)
}
func stringInSlice(s string, slice []string) bool {
for _, item := range slice {
if item == s {
return true
}
}
return false
}
func lowercaseSlice(slice []string) []string {
for index := range slice {
slice[index] = strings.ToLower(slice[index])
}
return slice
}
func perror(err error) {
if err != nil {
panic(err)
}
}
Owner

juliosantos commented May 17, 2015

API endpoints:

  • http://tlds.herokuapp.com/all returns a JSON array of all valid TLDs
  • http://tlds.herokuapp.com/check?tld=org returns true if org is a valid TLD, and false otherwise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment