0

I try to send the POST a request into my web server, but when i try to get response body occurs error. Also I tried to send request with Postman and everything worked fine. Response from server is JSON data which give some information about loaded picture. 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))
}
icza
  • 389,944
  • 63
  • 907
  • 827

1 Answers1

1

This is your line #42-43 where the error occurs:

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

If client.Do() returns an error, res may be nil, and so res.Body.Close() is a runtime panic. You have to first check the error, and only proceed to close the body if error is nil:

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

See related: Do we need to close the response object if an error occurs while calling http.Get(url)?

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

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you you really helped me. Thanked to you I found out that error occurred due to URL in which need add "http://" – defaultprogr Apr 12 '20 at 09:17