Skip to content

Instantly share code, notes, and snippets.

@mostlygeek
Created March 20, 2023 18:54
Show Gist options
  • Save mostlygeek/e3014cd97c67277391a04082c07670cc to your computer and use it in GitHub Desktop.
Save mostlygeek/e3014cd97c67277391a04082c07670cc to your computer and use it in GitHub Desktop.

Revisions

  1. mostlygeek created this gist Mar 20, 2023.
    70 changes: 70 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    package main

    /*
    This was entirely generated by GPT4 with the prompt:
    write me a simple golang server demonstrating server sent events (sse)
    */

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

    func main() {
    http.HandleFunc("/", serveHome)
    http.HandleFunc("/sse", serveSSE)
    http.ListenAndServe(":8080", nil)
    }

    func serveHome(w http.ResponseWriter, r *http.Request) {
    html := `<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Server-Sent Events Demo</title>
    </head>
    <body>
    <h1>Server-Sent Events Demo</h1>
    <div id="events"></div>
    <script>
    const eventSource = new EventSource("/sse");
    eventSource.onmessage = (event) => {
    const eventsDiv = document.getElementById("events");
    eventsDiv.innerHTML += "<p>" + event.data + "</p>";
    };
    eventSource.onerror = () => {
    console.error("Error occurred in EventSource connection.");
    };
    </script>
    </body>
    </html>`
    w.Header().Set("Content-Type", "text/html")
    w.Write([]byte(html))
    }

    func serveSSE(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, ok := w.(http.Flusher)
    if !ok {
    http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
    return
    }

    for i := 1; ; i++ {
    fmt.Fprintf(w, "data: Message %d from server\n\n", i)
    flusher.Flush()
    time.Sleep(time.Second)
    }

    }