Implementing a context timeout on each request using golang

I am trying to process a context timeout for each request. We have the following server structures:

enter image description here

Stream Overview:

Go server : basically acts as a [reverse proxy]. 2

Auth Server : Check for Authentication Requests.

Application Server : the logic for processing the main request.

Now, if the authorization server cannot process the request at the agreed time, I want to close goroutine from memory.

Here is what I tried:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequest("GET", authorizationServer, nil)
req.Header = r.Header
req.WithContext(ctx)
res, error := client.Do(req)
select {
case <-time.After(10 * time.Second):
    fmt.Println("overslept")
case <-ctx.Done():
    fmt.Println(ctx.Err()) // prints "context deadline exceeded"
}

" ", . . (goroutine), .

, 60 :

var netTransport = &http.Transport{
    Dial: (&net.Dialer{
        Timeout: 60 * time.Second,
    }).Dial,
    TLSHandshakeTimeout: 60 * time.Second,
}
client := &http.Client{
    Timeout:   time.Second * 60,
    Transport: netTransport,
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    },
}

- ? .

1. . - (goroutine), HTTP-, .

+4
1

, , .

5 seconds. request . , 2 . select 10 . 5 , .

context , , . , defer.

-. ctx.Err() deadline exceeded , . context. ctx.Err() .

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

go func () {
    select {
    case <-time.After(10 * time.Second):
        fmt.Println("overslept")
    case <-ctx.Done():
        fmt.Println(ctx.Err()) // prints "context deadline exceeded"
    }
}()
req, _ := http.NewRequest("GET", authorizationServer, nil)
req.Header = r.Header
req = req.WithContext(ctx)
res, error := client.Do(req)

:

// Err returns a non-nil error value after Done is closed. Err returns
// Canceled if the context was canceled or DeadlineExceeded if the
// context deadline passed. No other values for Err are defined.
// After Done is closed, successive calls to Err return the same value.

- , DeadlineExceeeded. , , , 10 . - .

error, client.Do, context . . - , , , , .

+7

Source: https://habr.com/ru/post/1674469/


All Articles