You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.1 KiB
Go

package main
import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"strings"
"time"
)
func SSEHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
tokens := strings.Split("Hey there Drew. I hope you enjoy The Alters!", " ")
for _, token := range tokens {
w.Write([]byte(fmt.Sprintf("data: %s \n\n", token)))
w.(http.Flusher).Flush()
time.Sleep(time.Millisecond * 420)
}
}
func routes() http.Handler {
// TODO add static server and an HTML index with `new EventSource` JS that writes the data message contents into an element on the page
mux := http.NewServeMux()
mux.HandleFunc("/sse", SSEHandler)
return mux
}
func run(ctx context.Context, w io.Writer, args []string) error {
addr := fmt.Sprintf("%s:%d", "0.0.0.0", 8888)
srv := &http.Server{
Addr: addr,
Handler: routes(),
}
slog.Info("Listing on: http://0.0.0.0:8888")
return srv.ListenAndServe()
}
func main() {
ctx := context.Background()
if err := run(ctx, os.Stdout, os.Args); err != nil {
slog.Error("an error occurred", "error", err)
}
}