Skip to content

Instantly share code, notes, and snippets.

@kostanovych
Created October 17, 2018 22:25
Show Gist options
  • Save kostanovych/d95bedf12a01b9fc3b5677f41ab9b548 to your computer and use it in GitHub Desktop.
Save kostanovych/d95bedf12a01b9fc3b5677f41ab9b548 to your computer and use it in GitHub Desktop.
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)
}
@wangmengyu
Copy link

for {
select {
case
}
}
will be better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment