Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created September 8, 2012 22:52
Show Gist options
  • Save chrisguitarguy/3680632 to your computer and use it in GitHub Desktop.
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.
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