-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (72 loc) · 2.22 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime"
"github.com/buarki/find-castles/castle"
"github.com/buarki/find-castles/enricher"
"github.com/buarki/find-castles/executor"
"github.com/buarki/find-castles/htmlfetcher"
"github.com/buarki/find-castles/httpclient"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("missing PORT env var")
}
httpClient := httpclient.New()
enrichers := map[castle.Country]enricher.Enricher{
castle.Ireland: enricher.NewIrishEnricher(httpClient, htmlfetcher.Fetch),
castle.Portugal: enricher.NewPortugueseEnricher(httpClient, htmlfetcher.Fetch),
castle.UK: enricher.NewBritishEnricher(httpClient, htmlfetcher.Fetch),
}
castlesEnricher := executor.New(runtime.NumCPU(), httpClient, enrichers)
fs := http.FileServer(http.Dir("./cmd/standalone/public"))
http.Handle("/", fs)
http.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
enrichedCastles, enrichmentErrs := castlesEnricher.Enrich(r.Context())
for {
select {
case <-r.Context().Done():
log.Println("request was canceled")
return
case err, ok := <-enrichmentErrs:
if ok {
log.Println("received error:", err)
}
case castle, ok := <-enrichedCastles:
if ok {
cb, err := json.Marshal(castle)
if err != nil {
log.Printf("failed to marshal castle [%s]: %v", castle.Name, err)
}
if _, err := fmt.Fprintf(w, "data: {\"message\": %s}\n\n", string(cb)); err != nil {
log.Printf("failed to write to response: %v", err)
}
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
} else {
log.Println("response writer does not support flushing")
}
} else {
fmt.Fprintf(w, "data: {\"finished\":\"finished\"}\n\n")
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
} else {
log.Println("response writer does not support flushing")
}
log.Println("finished processing castles")
return
}
}
}
})
fmt.Println("Server listening on port ", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}