gpt4 book ai didi

执行 HTTP 请求时出错

转载 作者:IT王子 更新时间:2023-10-29 01:58:01 25 4
gpt4 key购买 nike

运行以下http客户端对web服务器进行压力测试时,出现奇怪的错误,请问是什么原因。 go 的版本是 go1.8.1 linux/amd64 运行在 16GB 内存的 Ubuntu 14.04 上。

$ go run te2.go 
563.904492ms
Get http://10.3.0.6/small: dial tcp 10.3.0.6:80: connect: cannot assign requested address
Get http://10.3.0.6/small: dial tcp 10.3.0.6:80: connect: cannot assign requested address
Get http://10.3.0.6/small: dial tcp 10.3.0.6:80: connect: cannot assign requested address
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x5e3b27]

goroutine 140284 [running]:
main.httpGet(0x0)
/home/jon/learn/go/te2.go:27 +0x107
created by main.main
/home/jon/learn/go/te2.go:45 +0xd3
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x5e3b27]

goroutine 140375 [running]:
main.httpGet(0x0)
/home/jon/learn/go/te2.go:27 +0x107
created by main.main
/home/jon/learn/go/te2.go:45 +0xd3
exit status 2

有什么想法吗?

这是代码片段:

package main

import "fmt"
import "bufio"
import "os"
import "time"
import "net/http"

var req = []byte("GET /small HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Content-Length: 0\r\n\r\n");
var buf = make([]byte, 1024)
var total = 0;
var t0 = time.Now()
var c = make(chan int)

func httpGet () int {
req, err := http.NewRequest("GET", "http://10.3.0.6/small", nil)
//req.Header.Add("User-Agent", `MYCLIENT`)
//req.Header.Add("Cookie", `sessid=12345`)
client := &http.Client{}
resp, err := client.Do(req)
//defer resp.Body.Close()
if (err != nil) {
fmt.Println(err)
}
resp.Body.Close()
total ++
if (total == 10000) {
fmt.Println(time.Now().Sub(t0))
}
c <- 1
return 0;
}

func main() {
i := 1
t0 = time.Now()
for (i < 1000) {
go httpGet()
i += 1
}
for (1 < 2) {
<-c
go httpGet()
}
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
fmt.Println(text)
}

最佳答案

resp, err := client.Do(req)
//defer resp.Body.Close()
if (err != nil) {
fmt.Println(err)
}
resp.Body.Close()

在此片段中,您正在检查 err 并继续执行。

因此,如果发生某些事情并且 err 不是 nil,但 resp 是(或 resp.Body is) - 你打印错误然后取消引用一个 nil 指针。

你应该做的:如果发生错误 - 清理并从函数返回。

关于执行 HTTP 请求时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com