1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go: Server Sent Events のサンプル

Last updated at Posted at 2021-05-19

こちらのページと同じことを行いました。
Go言語でServerSentEvents(SSE)

go_server_sent_events.png

フォルダー構成

$ 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/
にアクセスします。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?