Created
May 17, 2015 16:39
-
-
Save juliosantos/9ba32e8ef00781f3b3a6 to your computer and use it in GitHub Desktop.
Go web API for TLD checking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
API endpoints:
http://tlds.herokuapp.com/all
returns a JSON array of all valid TLDshttp://tlds.herokuapp.com/check?tld=org
returnstrue
iforg
is a valid TLD, andfalse
otherwise