httpでテキストを取得するプログラムのテストケースを書いていますがgo testするとエラーになってしまいます。実行はできています。
Goを初めて間もないのでどうしたらいいか困っています。
go testの結果
bash
1$ go test 2--- FAIL: TestFetch (0.00s) 3panic: runtime error: invalid memory address or nil pointer dereference [recovered] 4 panic: runtime error: invalid memory address or nil pointer dereference 5[signal 0xc0000005 code=0x1 addr=0x0 pc=0x486cce]
メインソース
main.go
go
1package main 2 3import ( 4 "fmt" 5 "net/http" 6 "io/ioutil" 7) 8func main() { 9 fmt.Println(Fetch("http://dyn.value-domain.com/cgi-bin/dyn.fcg?ip")) 10} 11func Fetch(url string) (ip string, err error) { 12 c, e := http.Get(url) 13 defer c.Body.Close() 14 if e != nil { 15 err = e 16 return 17 } 18 b, _ := ioutil.ReadAll(c.Body) 19 return string(b), nil 20}
テストソース
main_test.go
go
1package main 2 3import ( 4 "testing" 5 "fmt" 6 "net/http" 7 "net/http/httptest" 8) 9 10func TestFetch(t *testing.T) { 11 ts := httptest.NewServer(nil) 12 defer ts.Close() 13 path := "/path/to/ip" 14 expected := "1.2.3.4" 15 http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { 16 fmt.Fprint(w, expected) 17 }) 18 actual, err := Fetch(ts.Config.Addr + path) 19 if err != nil { 20 t.Errorf("%s", err) 21 } 22 if actual != expected { 23 t.Errorf("got %v want %s", actual, expected) 24 } 25}
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/02 10:15
2015/11/02 10:18
2015/11/02 10:29 編集