How can I pause, or restart my go routine that is inside of my http handler func

Viewed 17

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)
        }

    }
}
0 Answers
Related