Created
October 17, 2018 22:25
-
-
Save kostanovych/d95bedf12a01b9fc3b5677f41ab9b548 to your computer and use it in GitHub Desktop.
Golang long polling example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
for {
select {
case
}
}
will be better.