为什么在尝试发送POST请求时发生错误?

时间:2020-04-12 07:45:51

标签: http go

我尝试将POST请求发送到我的Web服务器,但是当我尝试获取响应正文时发生错误。我也尝试与Postman发送请求,并且一切正常。服务器的响应是JSON数据,该数据提供了有关已加载图片的一些信息。 Error

package main

import (
    "fmt"
    "bytes"
    "mime/multipart"
    "os"
    "path/filepath"
    "io"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "localhost:6000/..."
    method := "POST"

    payload := &bytes.Buffer{}
    writer := multipart.NewWriter(payload)
    file, errFile1 := os.Open("/home/...")
    defer file.Close()
    part1, errFile1 := writer.CreateFormFile("Image",filepath.Base("/home/..."))
    _, errFile1 = io.Copy(part1, file)
    if errFile1 !=nil {    
    fmt.Println(errFile1)
    }
    err := writer.Close()
    if err != nil {
    fmt.Println(err)
    }


    client := &http.Client {
    }
    req, err := http.NewRequest(method, url, payload)

    if err != nil {
    fmt.Println(err)
    }
    req.Header.Set("Content-Type", writer.FormDataContentType())
    res, err := client.Do(req)
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    fmt.Println(string(body))
}

1 个答案:

答案 0 :(得分:1)

这是您的#42-43行中发生错误的地方:

res, err := client.Do(req)
defer res.Body.Close()

如果client.Do()返回错误,则res可能是nil,因此res.Body.Close()是运行时恐慌。您必须首先检查错误,并且只有在errornil时才继续关闭主体:

res, err := client.Do(req)
if err != nil {
    // Handle error and return:
    return
}
defer res.Body.Close()

查看相关内容:Do we need to close the response object if an error occurs while calling http.Get(url)?

也:Is resp.Body.Close() required if I don't need response?