Capture Timeout on GET request

Asked

Viewed 110 times

1

In my code I have an "attempt" to capture the timeout of the method Get package http but for some reason the mistake is not captured and a panic is displayed saying:

Get http://domain.site.com.br/endpoint: net/http: request canceled (Client.Timeout exceeded while awaiting headers)

Panic: Runtime error: invalid memory address or nil Pointer dereference

This request takes place within a goroutine.

request, err := http.NewRequest(method, endpoint, bytes.NewReader(data)) // data é nil
if err != nil {
    return nil, err
}

client := &http.Client{
    Timeout: 2 * time.Second,
}

response, err := client.Do(request)
if err != nil {
    fmt.Println(err.Error())
    return nil, Error{Message: err.Error(), Code: response.StatusCode}
}
defer response.Body.Close()

// TODO: For some reason the timeout handle is not working
if err, ok := err.(net.Error); ok && err.Timeout() {
    fmt.Println("timeout!") // não exibe a mensagem
    return nil, Error{Message: "timeout.", Code: http.StatusRequestTimeout}
}

On returning the Error i do a type checking with:

if err, ok := err.(commom.Error); ok {
    close(tube) // close the channel
    w.WriteHeader(err.Code)
    response.Encode(err)
    return
}

1 answer

1


The error occurred because another error was checked before the error of timeout

response, err := client.Do(request)
if err != nil {
    fmt.Println(err.Error())
    return nil, Error{Message: err.Error(), Code: response.StatusCode}
}

In the above case the variable response did not have StatuCode because the client closed the request due to the time of timeout.

The correct order of error checking is:

response, err := client.Do(request)
if err, ok := err.(net.Error); ok && err.Timeout() {
    return nil, Error{Message: "timeout.", Code: http.StatusRequestTimeout}
}
defer response.Body.Close()

if err != nil {
    fmt.Println(err.Error())
    return nil, Error{Message: err.Error(), Code: response.StatusCode}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.