-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (60 loc) · 1.37 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
package main
import (
_ "embed"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/btwiuse/sse"
)
func indexWith(s *sse.SSE) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
isIndex := r.URL.Path == "/"
isFavicon := r.URL.Path == "/favicon.ico"
isSSE := strings.Split(r.Header.Get("Accept"), ",")[0] == "text/event-stream"
isWS := strings.Split(r.Header.Get("Upgrade"), ",")[0] == "websocket"
if (isWS || isSSE) || !(isIndex || isFavicon) {
s.ServeHTTP(w, r)
return
}
switch {
case isIndex:
handleIndex(w, r)
case isFavicon:
http.Error(w, "", http.StatusOK)
}
})
}
func DateSSE() *sse.SSE {
sse := sse.NewSSE()
go (func() {
for {
now := time.Now().Format("2006-01-02 15:04:05")
sse.SetData(now)
time.Sleep(time.Second)
}
})()
return sse
}
//go:embed index.html
var IndexHtml string
func handleIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, IndexHtml)
}
func envPORT(p string) string {
PORT := p
if port, ok := os.LookupEnv("PORT"); ok {
PORT = ":" + port
}
return PORT
}
func main() {
port := envPORT(":8080")
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println(fmt.Sprintf("listening on http://127.0.0.1%s", port))
log.Fatalln(http.ListenAndServe(port, indexWith(DateSSE())))
}