0

I have a http handlerFunc that establishes a websocket connection.
If I get a websocket message start then I fire off a goroutine that will stream down some text/paragraphs of a story to the client.

Is it possible to stop a goroutine?

I want to stop/pause the goroutine if a I get another message like pause or stop, I would like to stop that goroutine. If I can't pause the goroutine, I would then like to know which sentence it was stopped at, and store that information somewhere so I can restart back at the same spot I stopped at.

Is this possible?

http.HandleFunc("/streamStory", streamStory)
log.Fatal(http.ListenAndServe(*addr, nil))

func streamStory(w http.ResponseWriter, r *http.Request) {
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Print("upgrade:", err)
        return
    }
    defer c.Close()
    

    for {
        mt, message, err := c.ReadMessage()
        if err != nil {
            log.Println("read:", err)
            break
        }
        if message == "start" {
          go doSomething(c)
        }

    }
}
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 1
    You can - but it's something you have to implement yourself (the runtime will not give you a [goroutine id](https://go.dev/doc/faq#no_goroutine_id) or similar). Cancellation is commonly handled via [`context`](https://pkg.go.dev/context#pkg-overview) and you can use channels to pass pause/resume requests (See [this question](https://stackoverflow.com/q/6807590/11810946) for some options). – Brits Sep 25 '22 at 01:26

0 Answers0