Created
September 8, 2012 22:52
-
-
Save chrisguitarguy/3680632 to your computer and use it in GitHub Desktop.
A simple URL status checker in Go. Made to practice a bit with channels and goroutines.
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 ( | |
"bufio" | |
"container/list" | |
"flag" | |
"fmt" | |
"net/http" | |
"io" | |
"os" | |
) | |
var file = flag.String("file", "", "The file to load") | |
type urlInfo struct { | |
Url, Status string | |
} | |
func read_file(fn string) *list.List { | |
f, err := os.Open(fn) | |
if err != nil { | |
panic(err) | |
} | |
l := list.New() | |
r := bufio.NewReader(f) | |
for { | |
line, _, err := r.ReadLine() | |
if err == io.EOF { | |
break; // end of the file | |
} | |
if err != nil { | |
fmt.Println(err) | |
continue | |
} | |
l.PushBack(string(line)) | |
} | |
return l | |
} | |
func fetch_url(url string, ch chan urlInfo) { | |
var i = urlInfo{Url: url} | |
if resp, err := http.Head(url); err != nil { | |
i.Status = "--" | |
} else { | |
i.Status = resp.Status | |
} | |
ch <- i | |
} | |
func main() { | |
flag.Parse() | |
l := read_file(*file) | |
ch := make(chan urlInfo, l.Len()) | |
for e := l.Front(); e != nil; e = e.Next() { | |
go fetch_url(e.Value.(string), ch) | |
} | |
var count = 0; | |
for { | |
u := <- ch | |
fmt.Println(u.Url, "\t", u.Status) | |
// seems like there's a better way to do this? | |
count++ | |
if count >= l.Len() { | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment