關於golang http.HttpClient.Do的問題

zradelaide1122發表於2016-10-20
func (c *Clients) PushData(reader io.Reader) error {
    log.Println("進入pushData")
    path := c.Slave.LocalFolder
    if strings.HasPrefix(path, "/") == false {
        path = "/" + path
    }
    buffer := new(bytes.Buffer)
    _, err := io.Copy(buffer, reader)
    if err != nil {
        log.Fatal(err)
        return err
    }

    contentType := http.DetectContentType(buffer.Bytes())
    params := map[string]string{}
    // log.Println(contentType, "contentType")
    params["Content-Type"] = contentType

    resp, err := c.DoRequest("PUT", path, params, buffer)

    if err != nil {
        log.Fatal(err)
        return err
    }

    body, _ := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()

    if resp.StatusCode != 200 {
        err := errors.New(resp.Status)
        log.Println(string(body))
        return err
    }
    return nil
}


func (c *Clients) DoRequest(method, path string, params map[string]string, data io.Reader) (*http.Response, error) {

    reqUrl := "http://" + c.Slave.IpAddr + path
    log.Println("進入reqUrl", reqUrl)
    req, _ := http.NewRequest(method, reqUrl, data)
    date := time.Now().UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")
    req.Header.Set("Date", date)
    req.Header.Set("Host", c.Master.IpAddr)
    if params != nil {
        for k, v := range params {
            req.Header.Set(k, v)
        }
    }

    if data != nil {
        req.Header.Set("Content-Length", strconv.Itoa(int(req.ContentLength)))
    }
    // log.Println(req)
    // c.HttpClient.Do(req)
    // c.HttpClient.Timeout = time.Duration(time.Second * 10)

    resp, err := c.HttpClient.Do(req)
    log.Fatal("==============================")
    log.Println(resp)
    log.Fatal(err)
    log.Fatal("==============================")

    return resp, err
}

關於這兩段程式碼在執行的時候 會在
resp, err := c.HttpClient.Do(req) 這邊丟擲一個

panic: runtime error: invalid memory address or nil pointer dereference
Äsignal SIGSEGV: segmentation violation code=0x1 addr=0x28 pc=0x830c6Ü

goroutine 5 ÄrunningÜ:
panic(0x389560, 0xc42000c0b0)
    /usr/local/go/src/runtime/panic.go:500 +0x1a1
net/http.(*Client).deadline(0x0, 0xc420166010, 0x420d7c, 0x5)
    /usr/local/go/src/net/http/client.go:193 +0x26
net/http.(*Client).doFollowingRedirects(0x0, 0xc4201c4000, 0x423400, 0x3, 0xb6901, 0xc420146210)
    /usr/local/go/src/net/http/client.go:446 +0x8b
net/http.(*Client).Do(0x0, 0xc4201c4000, 0xe, 0xc420176170, 0x5)
    /usr/local/go/src/net/http/client.go:187 +0x11d

的異常我看了下 這個地方是關於deadline的 嘗試了下給httpClient.TimeOut賦值還是會丟擲resp, err := c.HttpClient.Do(req)
panic: runtime error: invalid memory address or nil pointer dereference
Äsignal SIGSEGV: segmentation violation code=0x1 addr=0x28 pc=0x830c6Ü 這樣一個錯誤夜深寫的有點懵了。。。 希望高人指點下。。。

具體業務是put一個檔案到遠端資料夾。。。
更多原創文章乾貨分享,請關注公眾號
  • 關於golang http.HttpClient.Do的問題
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章