http - Server-initiated requests -
i know http request-response protocol. problem, in short, client makes request server start long running-process, , want inform client of progress simple json message containing progress info.
in http/1.1 know use websocket or server-sent events (sse) or long polling.
now know http/2 not support websocket yet.
my question is, optimal way handle such things on http/2?
are there new things not aware of handle server-initiated requests in http/2?
i using go language, if matters.
before websockets had polling. literally means having client periodically (every few seconds, or whatever time period makes sense application), make request server find out status of job.
an optimization many people use "long" polling. involves having server accept request, , internally server, check changes, , sleep while there none, until either specific timeout reached or desired event occurs, messaged client.
if timeout reached, connection closed , client needs make request. server code following, assume functions sensible things based on names , signatures:
import ( "net/http" "time" ) func pollinghandler(w http.responsewriter, r *http.request) { jobid := getjobid(r) finish := 60; finish > 0; finish-- { // iterate ~1 minute status, err := checkstatus(jobid) if err != nil { writeerror(w, err) return } if status != nil { writestatus(w, status) return } time.sleep(time.second) // sleep 1 second } writenil(w) // specific response telling client request again. }
a better way handle timeout use context package , create context timeout. like:
import ( "net/http" "time" "golang.org/x/net/context" ) func pollinghandler(w http.responsewriter, r *http.request) { jobid := getjobid(r) ctx := context.withtimeout(context.background(), time.second * 60) { select{ case <-ctx.done(): writenil(w) default: status, err := checkstatus(jobid) if err != nil { writeerror(w, err) return } if status != nil { writestatus(w, status) return } time.sleep(time.second) // sleep 1 second } } }
this second version going return in more reliable amount of time, in case checkstatus
may slower call.
Comments
Post a Comment