added url fetching

This commit is contained in:
Stephen McQuay 2017-05-12 13:44:54 -07:00
parent 68cd4b57da
commit c7378e2ae0
No known key found for this signature in database
GPG Key ID: 1ABF428F71BAFC3D
2 changed files with 53 additions and 0 deletions

26
fetch.go Normal file
View File

@ -0,0 +1,26 @@
package hmm
import (
"bufio"
"net/http"
)
// Lines returns a chan containing one line of output from the remote url.
func Lines(url string) <-chan string {
r := make(chan string)
go func() {
defer close(r)
resp, err := http.Get(url)
if err != nil {
return
}
s := bufio.NewScanner(resp.Body)
for s.Scan() {
r <- s.Text()
}
// ignore errors
}()
return r
}

27
fetch_test.go Normal file
View File

@ -0,0 +1,27 @@
package hmm
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
type dummy struct{}
func (d *dummy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for i := 0; i < 10; i++ {
fmt.Fprintf(w, "here is a line: %d\n", i)
}
}
func TestFetch(t *testing.T) {
ts := httptest.NewServer(&dummy{})
i := 0
for range Lines(ts.URL) {
i++
}
if got, want := i, 10; got != want {
t.Fatalf("got %d, want %d", got, want)
}
}