namecheck/cmd/server/main.go

71 lines
1.5 KiB
Go
Raw Normal View History

2019-12-04 16:58:38 +01:00
package main
import (
"fmt"
"io"
"log"
"net/http"
"sync"
"forge.cadoles.com/pcaseiro/namecheck"
"forge.cadoles.com/pcaseiro/namecheck/twitter"
)
func checkUsername(ch chan<- string, wg *sync.WaitGroup, sn namecheck.SocialNetwork, username string) (bool, error) {
defer wg.Done()
// s1 := rand.NewSource(time.Now().UnixNano())
// time.Sleep(rand.New(s1).Intn(100))
res, err := sn.IsAvailable(username)
if err != nil {
ch <- fmt.Sprintf("Error : {%v} for %v\n", err, sn.String())
return false, err
}
if !res {
ch <- fmt.Sprintf("User %s is not available on %v\n", username, sn.String())
return false, nil
}
ch <- fmt.Sprintf("User %s is available on %v\n", username, sn.String())
return true, nil
}
func msgHandler(w http.ResponseWriter, req *http.Request) {
var wg sync.WaitGroup
var socialNetworks []namecheck.SocialNetwork
// Create a channel for result
ch := make(chan string, 20)
// Create the "social networks"
for i := 0; i < 20; i++ {
socialNetworks = append(socialNetworks, &twitter.Twitter{})
}
// Start the routines for check
urlQuery := req.URL.Query() //os.Args[1]
usernames := urlQuery["u"]
for _, user := range usernames {
for _, sn := range socialNetworks {
wg.Add(1)
go checkUsername(ch, &wg, sn, user)
}
}
// Wait in background
go func() {
wg.Wait()
close(ch)
}()
// Print the result
for li := range ch {
io.WriteString(w, li)
}
}
func main() {
http.HandleFunc("/", msgHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}