-
Notifications
You must be signed in to change notification settings - Fork 216
/
main.go
60 lines (51 loc) · 1.26 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"context"
"fmt"
"log"
"math/rand"
"net/http"
"time"
)
// This is a simple example of a long poll server.
var timeout = time.Second * 5 //30
var maxOpMS = 8000 //60 * 1000 // 60 seconds -> 50% chance of StatusNotModified.
func init() {
rand.Seed(time.Now().Unix())
}
func operation(ctx context.Context, ch chan<- string) {
wait := time.Millisecond * time.Duration(rand.Intn(maxOpMS))
fmt.Printf(" -> Wait %v\n", wait)
select {
case <-time.After(wait):
ch <- fmt.Sprintf(`{"waited":"%v"}`, wait)
case <-ctx.Done():
fmt.Println(" -> Op canceled")
return
}
fmt.Println(" -> Op done")
}
func handler(w http.ResponseWriter, req *http.Request) {
fmt.Println("Request")
ch := make(chan string) // TODO: send real struct.
go operation(req.Context(), ch)
select {
case result := <-ch:
fmt.Println("Response")
_, _ = w.Write([]byte(result))
case <-time.After(timeout):
fmt.Println("Timeout")
w.WriteHeader(http.StatusNotModified)
case <-req.Context().Done():
fmt.Println("Client has disconnected")
}
close(ch)
fmt.Println("Done")
}
func main() {
addr := ":8181"
http.HandleFunc("/", handler)
server := &http.Server{Addr: addr, Handler: nil}
log.Printf("Starting on %s\n", addr)
log.Print(server.ListenAndServe())
}