こちらのページと同じことを行いました。
Go言語でServerSentEvents(SSE)
フォルダー構成
$ tree
.
├── main.go
└── static
└── index.html
main.go
// ---------------------------------------------------------------
//
// main.go
//
// May/19/2021
// ---------------------------------------------------------------
package main
import (
"fmt"
"os"
"log"
"net/http"
"time"
)
// ---------------------------------------------------------------
func sse(w http.ResponseWriter, r *http.Request) {
flusher, _ := w.(http.Flusher)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// 1秒おきにデータを流す
t := time.NewTicker(1 * time.Second)
defer t.Stop()
go func() {
cnt := 1
for {
select {
case <-t.C:
fmt.Fprintf(w, "data: %d\n\n", cnt)
cnt++
flusher.Flush()
}
}
}()
<-r.Context().Done()
log.Println("コネクションが閉じました")
}
// ---------------------------------------------------------------
func main() {
fmt.Fprintf (os.Stderr,"*** 開始 ***\n")
fmt.Fprintf (os.Stderr,"http://localhost:8080/\n")
dir := http.Dir("./static")
http.HandleFunc("/event", sse)
http.Handle("/", http.FileServer(dir))
http.ListenAndServe(":8080", nil)
fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}
// ---------------------------------------------------------------
static/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<title>Server Sent Events</title>
</head>
<body>
<h2>Server Sent Events</h2>
<blockquote>
<p>count: <span id="cnt">0</span></p>
</blockquote>
<script>
const ev = new EventSource('/event');
ev.addEventListener('message', (e) => {
cnt.textContent = e.data;
});
</script>
<hr />
May/19/2021 PM 17:40<br />
</body>
</html>
サーバーの起動
$ go run main.go
*** 開始 ***
http://localhost:8080/
ブラウザーで、
http://localhost:8080/
にアクセスします。