http - 为什么我尝试发送 POST 请求时出现错误?

标签 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))
}

最佳答案

这是发生错误的第 42-43 行:

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

如果 client.Do()返回错误,res可能是 nil ,等等res.Body.Close()是运行时 panic 。您必须首先检查错误,并且只有在 error 时才继续关闭正文是 nil :
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?

关于http - 为什么我尝试发送 POST 请求时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61168305/

相关文章:

ruby http连接池

java - HttpServletRequest 读取大型帖子正文 - 无法读取所有数据,等待所有 block

html - 使用 Go 解析 HTML 文件

json - 在 Go 中将 Json 数据解码到 map 中

json - Golang JSON Unmarshal 序列号

golang otto 加载JS报错

http - Flutter 内置值反序列化'由于 : Tried to build class but nested builder for field threw: Tried to construct class with null field 而失败

c++ - 有没有类似于 apache httpcomponents 的 C/C++ 库?

apache - 重用并添加到 500 错误以从 soap 获得更好的统计数据

python - Google App Engine mail.Send 在 python2.7/smtplib.py 中返回 "TypeError: unhashable instance"