Use WebSockets for full-duplex, low-latency bidirectional communication and Server-Sent Events (SSE) for unidirectional server-to-client streaming. WebSockets require a third-party library like gorilla/websocket to handle the protocol upgrade, while SSE uses the standard net/http package and relies on ResponseWriter.Flush() for streaming. For a simple server-to-client notification system, SSE is the easiest implementation:
func handler(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")
flusher, _ := w.(http.Flusher)
for {
fmt.Fprintf(w, "data: %s\n\n", "Hello")
flusher.Flush()
time.Sleep(1 * time.Second)
}
}
For bidirectional chat, use gorilla/websocket to upgrade the connection:
import "github.com/gorilla/websocket"
var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
func handler(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
for {
_, msg, _ := conn.ReadMessage()
conn.WriteMessage(websocket.TextMessage, msg)
}
}