package main import ( "embed" "fmt" "html/template" "net/http" "os" "github.com/sirupsen/logrus" "gitlab.com/mstarongitlab/weblogger" ) const HTML_PREFIX = "" //go:embed templates var embed_templates embed.FS //go:embed static var embed_static embed.FS //go:embed well-known var embed_well_known embed.FS // go: embed robots.txt var embed_robots_txt string // go: embed humans.txt var embed_humans_txt string func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } logrus.WithField("port", port).Info("starting server") // Custom-ish paths. Includes templates http.HandleFunc("/", handleRoot) // Funny awawawa stream http.HandleFunc("/cat/awawawa", awawaStream) // static files in /static http.Handle("/static/", http.FileServer(http.FS(embed_static))) // .well-known from /well-known http.Handle("/.well-known/", http.StripPrefix("/.well-known/", http.FileServer(http.FS(embed_well_known)))) // Static files not in /static or /.well-known http.HandleFunc("/robots.txt", buildHTTPFileReader(embed_robots_txt)) http.HandleFunc("/humans.txt", buildHTTPFileReader(embed_humans_txt)) default_mux := http.DefaultServeMux logger := weblogger.LoggingMiddleware(default_mux) if err := http.ListenAndServe(":"+port, logger); err != nil { logrus.WithField("event", "stop server").Fatal(err) } } func handleRoot(w http.ResponseWriter, r *http.Request) { // logRequestInfo(r) 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) { // logRequestInfo(r) fmt.Fprintf(w, "%s", embed_content) } } func awawaStream(w http.ResponseWriter, r *http.Request) { 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 fmt.Println("Starting awawawa stream") i := 0 for { select { case <-r.Context().Done(): fmt.Println("awawawa Stream done") return default: if i%2 == 0 { fmt.Fprint(w, "a") } else { fmt.Fprint(w, "w") } i += 1 } } } 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) }