package main
import (
"fmt"
"html/template"
"net/http"
"time"
"github.com/rs/zerolog/hlog"
"github.com/rs/zerolog/log"
"git.mstar.dev/mstar/mstar-webserver/storage"
)
func handleRoot(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFS(embed_templates, "templates/index.html")
if err != nil {
http.Error(w, "Couldn't parse template file", http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, nil)
if err != nil {
http.Error(w, "Failed to execute template", http.StatusInternalServerError)
}
}
func buildHTTPFileReader(embed_content string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", embed_content)
}
}
func countingRedirect(target string) http.Handler {
redirect := http.RedirectHandler(target, http.StatusMovedPermanently)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Info().Msg("Counting redirect")
fmt.Println("Counting redirect")
if err := storage.IncrementLinkCounter(target); err != nil {
log.Error().Err(err).Str("target", target).Msg("Failed to update link")
}
redirect.ServeHTTP(w, r)
})
}
func awawaStream(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Disabled until I can find a good way to rate limit the stream")
return
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(206)
w.Header().Set("Status", "206")
genStub(
1024,
w,
) // Hardcoded. Firefox & Chrome both have this value and a len of 0 wouldn't work
hlog.FromRequest(r).Debug().Msg("Starting stream")
i := true
fmt.Fprint(w, "awawaw")
// Only run every 0.2 seconds, aka 5 times a second
timer := time.Tick(time.Millisecond * 100)
for {
select {
case <-r.Context().Done():
hlog.FromRequest(r).Debug().Msg("Stream done")
return
case <-timer:
hlog.FromRequest(r).Debug().Msg("Stream elem")
if i {
fmt.Fprint(w, "a")
} else {
fmt.Fprint(w, "w")
}
i = !i
}
}
}
func genStub(length int, w http.ResponseWriter) {
PreSufLen := len(HTML_PREFIX) + len(HTML_SUFFIX)
fmt.Fprint(w, HTML_PREFIX)
for i := 0; i < length-PreSufLen; i++ {
fmt.Fprint(w, '\u0020')
}
fmt.Fprint(w, HTML_SUFFIX)
}