Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use request.Context instead of CloseNotifier?

Tags:

go

I am using CloseNotifier in my application, in a code that looks like this

func Handler(res http.ResonseWriter, req *http.Request) {
    notify := res.(CloseNotifier).CloseNotify()

    someLogic();
    select {
        case <-notify:
            someCleanup()
            return;
        default:
    }
    someOtherLogic();
}

I have noticed CloseNotifier is now deprecated. From source code:

// Deprecated: the CloseNotifier interface predates Go's context package.
// New code should use Request.Context instead.

However, I am not sure how to use Request.Context exactly here.

like image 267
Karel Bílek Avatar asked Feb 26 '19 17:02

Karel Bílek


1 Answers

It seems rather simple actually. From this blogpost:

func Handler(res http.ResonseWriter, req *http.Request) {
    ctx := req.Context()

    someLogic();
    select {
        case <-ctx.Done():
            someCleanup(ctx.Err())
            return;
        default:
    }
    someOtherLogic();
}
like image 66
Karel Bílek Avatar answered Nov 18 '22 06:11

Karel Bílek