requisition to bad URL makes my golang http request crash my main thread

-1

What I expected:
To receive any HTTP status code for given requisition.

What I got:
exit status 2.

What I think:
Probably an error on transportation layer? But I don't know how to treat it.

Code to reproduce given error:

package main

import (
    "fmt"
    "net/http"
    "strings"
)

func main() {
    url := "http://32.67.163.173:9200/suprin/_doc/"
    requestType := "POST"
    body := strings.NewReader("")

    req, err := http.NewRequest(requestType, url, body)
    if err != nil {
        fmt.Println("Unable to create the request: " + err.Error())
    }

    fmt.Println("1")
    req.Header.Set("Content-Type", "application/json")
    fmt.Println("2")
    resp, err := http.DefaultClient.Do(req)
    fmt.Println("3")

    if resp.StatusCode != 201 {
        fmt.Println("4")
        fmt.Println("httpe error: " + resp.Status)
    }
    fmt.Println("5")
}

My error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x62c413]

goroutine 1 [running]:
main.main()
        C:/Users/Luado/Desktop/Goling-in-the rain/http_req_broken_url/http_req.go:25 +0x2e3
exit status 2

My request: I wish to correctly treat this error, but I'm unsure how, so my application can end gracefully.

http
go
asked on Stack Overflow Sep 10, 2020 by Pessoa • edited Sep 11, 2020 by Pessoa

1 Answer

1

Handle every error in GO.

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
╰─# go run main.go                                                                                                      1 ↵
1
2
Post "http://32.67.163.173:9200/suprin/_doc/": dial tcp 32.67.163.173:9200: connect: connection refused
answered on Stack Overflow Sep 11, 2020 by p1gd0g

User contributions licensed under CC BY-SA 3.0