> On 19 Apr 2021, at 10:07 pm, Amit Saha <[email protected]> wrote:
>
> Thank you, I was suspecting that this might be the way to do it.
This is another approach I thought would also work without using channels or
where you are just running a sequence of steps in a handler:
func handleUserAPI(w http.ResponseWriter, r *http.Request) {
log.Println("I started processing the request")
time.Sleep(15 * time.Second)
log.Println("Before continuing, i will check if the timeout has already
expired")
if r.Context().Err() != nil {
log.Printf("Aborting further processing: %v\n",
r.Context().Err())
return
}
fmt.Fprintf(w, "Hello world!")
log.Println("I finished processing the request")
}
>
>
>
>
> On Mon, 19 Apr 2021, 6:02 pm Brian Candler, <[email protected]
> <mailto:[email protected]>> wrote:
> Your inner request handler needs to use the request context to cancel its
> work.
>
> package main
>
> import (
> "log"
> "net/http"
> "time"
> )
>
> type foo struct{}
>
> func (f foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
> log.Print("New request")
> for i := 0; i < 10; i++ {
> select {
> case <-r.Context().Done():
> log.Print("Aborted")
> return
> case <-time.After(1 * time.Second):
> log.Print("Tick")
> }
> w.Write([]byte(".\n"))
> }
> w.Write([]byte("hello world\n"))
> log.Print("Completed")
> }
>
> func main() {
> fooHandler := foo{}
> timeoutHandler := http.TimeoutHandler(fooHandler, 5*time.Second, "Too
> slow!\n")
> http.Handle("/foo", timeoutHandler)
> log.Fatal(http.ListenAndServe(":8080", nil))
> }
>
> To test:
> curl localhost:8080/foo
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected]
> <mailto:[email protected]>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/d75657a2-5ab5-4908-9997-3fe3dfe3b87an%40googlegroups.com
>
> <https://groups.google.com/d/msgid/golang-nuts/d75657a2-5ab5-4908-9997-3fe3dfe3b87an%40googlegroups.com?utm_medium=email&utm_source=footer>.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/40B6DCC5-A321-4AF8-A03B-F5A0CFD18989%40gmail.com.