go - 运行时错误 : invalid memory address or nil pointer dereference

标签 go

我是新手,正在尝试制作一个简单的网络爬虫。我不断收到“ panic :运行时错误:无效内存地址或零指针取消引用”并且不知道如何解决该问题。我有一个“advancedFetcher”函数和一个“basicFetcher”函数,但我在其中任何一个下都遇到了相同的错误。 This answer建议检查每个错误(我认为是这样),但我仍然遇到错误。谢谢!

package main

import (
    "crypto/tls"
    "fmt"
    "io/ioutil"
    "net"
    "net/http"
    "time"
)

var tr = &http.Transport{
    TLSClientConfig:     &tls.Config{InsecureSkipVerify: true},
    MaxIdleConnsPerHost: 25,
    DisableKeepAlives:   true,
    Proxy:               http.ProxyFromEnvironment,
    Dial: (&net.Dialer{
        Timeout:   10 * time.Second,
        KeepAlive: 10 * time.Second,
    }).Dial,
    TLSHandshakeTimeout: 5 * time.Second,
}
var client = &http.Client{Transport: tr}

func makeGetRequest(uri string) *http.Response {
    req, err := http.NewRequest("GET", uri, nil)
    if err != nil {
        fmt.Println(err)
    }
    req.Header.Add("User-Agent", "Hi it's me again")
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
    }
    return resp
}

func advancedFetcher(uri string, c chan int) {
    fmt.Println("Getting: ", uri)
    resp := makeGetRequest(uri)
    defer resp.Body.Close()
    c <- resp.StatusCode
}

func basicFetcher(uri string, c chan int) {
    fmt.Println("Getting: ", uri)
    resp, err := http.Get(uri)
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()
    _, err = ioutil.ReadAll(resp.Body)
    c <- resp.StatusCode
}

func main() {
    c := make(chan int)
    rows := []string{"https://www.google.com", "http://www.fdicconnect.gov"}
    for _, row := range rows {
        //go basicFetcher(row, c)
        go advancedFetcher(row, c)
    }
    for _ = range rows {
        select {
        case result := <-c:
            fmt.Println(result)
        }
    }
    fmt.Println("All Done")
}

编辑#1:

Getting:  https://www.google.com
Getting:  http://www.fdicconnect.gov
200
Get http://www.fdicconnect.gov: dial tcp 167.176.6.86:80: i/o timeout
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x400ff2]

goroutine 21 [running]:
runtime.panic(0x6594c0, 0x7e9b53)
    /usr/local/go/src/pkg/runtime/panic.c:279 +0xf5
main.advancedFetcher(0x6c3b70, 0x1a, 0xc208004180)
    /home/me/go/src/testfolder/tester/main.go:41 +0x1c2
created by main.main
    /home/me/go/src/testfolder/tester/main.go:61 +0x123

goroutine 16 [chan receive]:
main.main()
    /home/me/go/src/testfolder/tester/main.go:65 +0x198

goroutine 19 [finalizer wait]:
runtime.park(0x413bd0, 0x7ee660, 0x7ec8c9)
    /usr/local/go/src/pkg/runtime/proc.c:1369 +0x89
runtime.parkunlock(0x7ee660, 0x7ec8c9)
    /usr/local/go/src/pkg/runtime/proc.c:1385 +0x3b
runfinq()
    /usr/local/go/src/pkg/runtime/mgc0.c:2644 +0xcf
runtime.goexit()
    /usr/local/go/src/pkg/runtime/proc.c:1445

goroutine 17 [syscall]:
runtime.goexit()
    /usr/local/go/src/pkg/runtime/proc.c:1445

最佳答案

您的程序在 panic 之前是否打印错误?如果没记错的话,如果http.Get返回错误,那么resp.Body == nil,这会导致你的错误,因为你不能调用resp。 Body.Close()nil 上。

作为twotwotwo suggests ,你应该编写你的函数,以便它返回一个(结果,错误)对,这样你就可以在遇到问题之前优雅地终止它。

关于go - 运行时错误 : invalid memory address or nil pointer dereference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26726203/

相关文章:

go - 无法运行 goinstall

mongodb - UpdateOne、ReplaceOne、FindOneAndReplace - 模式匹配,但没有更新数据

php - 如何复制 openssl_encrypt?

http - 写一个临时响应 - 去服务器

go - 如何在 The Go Programming Language 中实现练习

python - Golang 相当于 pythons __getattr__() 或 __call__()

go - 如何完全禁用 HTTP/1.x 支持

go - 如何在 gRPC 中使用预定义的 protobuf 类型(即 "google/protobuf/timestamp.proto")

golang 转换包含 unicode 的字节数组

swift - Go 的空界面是否有 swift 的等价物?