使用Client.Do

时间:2019-01-28 09:44:24

标签: http go

尝试发送多个http.ReadRequest生成的同一HTTP请求,出现以下错误:

Post http://192.168.x.x:8000/dir1: http: invalid Read on closed Body
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x5ec4cc]

我的代码获取一个文件,并将其放入bufio.NewReader中。然后,它对已读取的内容使用http.ReadRequest,这是一个HTTP POST请求。最后-打开另一个文件“ wordlist.txt”,其中包含目录-并每次使用列表中的其他目录遍历原始HTTP URI。 由于某些原因-第二个请求导致编程错误(http: invalid Read on closed Body)。这是一个有效的示例(只需更改您的路径即可):

main.go

package main

import (
    "bufio"
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
)

func main() {
    //Read HTTP request from text file
    rdr, err := os.Open("/opt/gohttp/tests/req2.txt")
    if err != nil {
        log.Println(err)
    }

    //Parse to a web request to work with using ReadRequest
    req, err := http.ReadRequest(bufio.NewReader(rdr))
    if err != nil {
        log.Println(err)
    }

    // fix for "requestURI can't be sent in client requests"
    req.RequestURI = ""

    //Open wordlist
    file, err := os.Open("/opt/gohttp/tests/wordlist.txt")
    if err != nil {
        log.Println(err)
    }
    defer file.Close()

    //Scan wordlist line by line and append each to the directory
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        var i string = scanner.Text()
        fmt.Println(i)
        //this part appends the wordlist word to the request sent e.g. /dir1
        u, err := url.Parse("http://" + req.Host + "/" + i) //todo: https? other protocols?
        if err != nil {
            log.Println("scanner parse error: ", err)
        }
        req.URL = u

        //Send the request
        fmt.Println("Sending request.." + "\n")
        client := &http.Client{}
        response, err := client.Do(req)
        if err != nil {
            log.Println(err) // invalid read on closed body error
        }
        fmt.Println(*response)
    }
    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }

}

HTTP请求文件示例

POST /hi HTTP/1.1
Host: 192.168.x.x:8000
Content-Length: 41

{"email":"aa","password":"secret"}

单词列表文件示例

0
1
dir1
dir2
dir3

应用程序输出

go run tests/main.go

0
Sending request..

{404 Not Found 404 HTTP/1.1 1 1...}

1
Sending request..

2019/01/28 04:27:52 Post http://192.168.x.x:8000/1: http: invalid Read on closed Body
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x5ec4cc]

goroutine 1 [running]:
main.main()
    /opt/gohttp/tests/main.go:53 +0x35c
exit status 2

请注意,第一个HTTP请求已成功发送,只有第二个HTTP请求返回上述错误。我该如何解决?

0 个答案:

没有答案