~thewhodidthis/longform

5743623f421388de0c79916d80da0d47ee5faca1 — thewhodidthis a month ago 00692c9
go: clean up
1 files changed, 20 insertions(+), 13 deletions(-)

M main.go
M main.go => main.go +20 -13
@@ 60,13 60,29 @@ type Tracker struct {
}

func (t *Tracker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if !strings.HasSuffix(r.URL.Path, "/io") {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		log.Printf("ServeHTTP: odd path: %s", r.URL.Path)

		return
	}

	// Need to manually flush the response writer for SSE to work.
	f, ok := w.(http.Flusher)

	if !ok {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)

		return
	}

	if a := r.Header.Get("Accept"); a != "text/event-stream" {
		http.Error(w, http.StatusText(http.StatusNotAcceptable), http.StatusNotAcceptable)

		return
	}

	if o := r.Header.Get("Origin"); o != "" {
	if o := r.Header.Get("Origin"); strings.Contains(o, "localhost") {
		w.Header().Set("Access-Control-Allow-Origin", o)
	}



@@ 74,14 90,6 @@ func (t *Tracker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Content-Type", "text/event-stream")

	f, ok := w.(http.Flusher)

	if !ok {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)

		return
	}

	c := make(chan string)

	defer func() {


@@ 95,13 103,12 @@ func (t *Tracker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
L:
	for {
		select {
		case txt := <-c:
			fmt.Fprintf(w, "retry: 10000\ndata: %s\n\n", txt)
		case d := <-c:
			fmt.Fprintf(w, "retry: 10000\ndata: %s\n\n", d)
			f.Flush()
		case <-r.Context().Done():
			break L
		}

		f.Flush()
	}
}