package main
import (
"context"
"fmt"
"html/template"
//"io"
"log/slog"
"net/http"
//"os"
"strings"
"time"
)
func IndexHandler(w http.ResponseWriter, r *http.Request) {
files := []string{
"./ui/html/base.go.tmpl",
"./ui/html/index.go.tmpl",
}
ts, err := template.ParseFiles(files...)
if err != nil {
slog.Error("error parsing files", "error", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = ts.ExecuteTemplate(w, "base", nil)
if err != nil {
slog.Error("error executing template", "error", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
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 {
fileServer := http.FileServer(http.Dir("./ui/static/"))
mux := http.NewServeMux()
mux.Handle("GET /static/", http.StripPrefix("/static", fileServer))
mux.HandleFunc("GET /sse", SSEHandler)
mux.HandleFunc("GET /{$}", IndexHandler)
return mux
}
// TODO add args slice and process flags
// TODO add io.Writer and pass that to the logger
func run(ctx context.Context) 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()
// TODO add os.Args
if err := run(ctx); err != nil {
slog.Error("an error occurred", "error", err)
}
}