Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang long polling example
package main
import (
"fmt"
"net/http"
"time"
)
func longOperation(ch chan<- string) {
// Simulate long operation.
// Change it to more than 10 seconds to get server timeout.
time.Sleep(time.Second * 3)
ch <- "Successful result."
}
func handler(w http.ResponseWriter, _ *http.Request) {
ch := make(chan string)
go longOperation(ch)
select {
case result := <-ch:
fmt.Fprint(w, result)
case <-time.After(time.Second * 10):
fmt.Fprint(w, "Server is busy.")
<-ch
}
close(ch)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment