2025/03/01

使用 Go Lang 撰寫一個 SSE(Server-Sent Events) Testing Server


package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

func sseHandler(w http.ResponseWriter, r *http.Request) {
	// 設置 SSE 頭
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")

	// 強制刷新,以保持連接
	flusher, ok := w.(http.Flusher)
	if !ok {
		log.Fatal("Server does not support HTTP streaming.")
	}

	// 連接時顯示訊息
	log.Printf("新用戶連接:%s", r.RemoteAddr)

	// 模擬逐步發送 SSE 資料
	for i := 1; i <= 3; i++ {
		// 顯示正在發送資料
		log.Printf("開始發送第 %d 條資料", i)

		// 模擬 SSE 資料
		fmt.Fprintf(w, "data: 第一段資料 %d\n\n", i)
		flusher.Flush() // 刷新資料

		time.Sleep(3 * time.Second) // 模擬延遲
	}

	// 完成 SSE 流
	fmt.Fprintf(w, "data: SSE 流結束\n\n")
	flusher.Flush()

	// 完成後顯示訊息
	log.Printf("完成發送資料給 %s", r.RemoteAddr)
}

func main() {
	http.HandleFunc("/sse", sseHandler)

	log.Println("伺服器啟動,請訪問 http://localhost:8080/sse")
	log.Fatal(http.ListenAndServe(":8080", nil))
}