package global import ( "fmt" "net/http" "os" "path/filepath" "html/template" "strconv" "time" "arimelody.me/arimelody.me/colour" ) func DefaultHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Server", "arimelody.me") w.Header().Add("Cache-Control", "max-age=2592000") next.ServeHTTP(w, r) }) } type LoggingResponseWriter struct { http.ResponseWriter Code int } func (lrw *LoggingResponseWriter) WriteHeader(code int) { lrw.Code = code lrw.ResponseWriter.WriteHeader(code) } func HTTPLog(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() lrw := LoggingResponseWriter{w, http.StatusOK} next.ServeHTTP(&lrw, r) after := time.Now() difference := (after.Nanosecond() - start.Nanosecond()) / 1_000_000 elapsed := "<1" if difference >= 1 { elapsed = strconv.Itoa(difference) } codeColour := colour.Reset if lrw.Code - 600 <= 0 { codeColour = colour.Red } if lrw.Code - 500 <= 0 { codeColour = colour.Yellow } if lrw.Code - 400 <= 0 { codeColour = colour.White } if lrw.Code - 300 <= 0 { codeColour = colour.Green } fmt.Printf("[%s] %s %s - %s%d%s (%sms) (%s)\n", after.Format(time.UnixDate), r.Method, r.URL.Path, codeColour, lrw.Code, colour.Reset, elapsed, r.Header["User-Agent"][0]) }) } func ServeTemplate(page string, data any) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { lp_layout := filepath.Join("views", "layout.html") lp_header := filepath.Join("views", "header.html") lp_footer := filepath.Join("views", "footer.html") lp_prideflag := filepath.Join("views", "prideflag.html") fp := filepath.Join("views", filepath.Clean(page)) info, err := os.Stat(fp) if err != nil { if os.IsNotExist(err) { http.NotFound(w, r) return } } if info.IsDir() { http.NotFound(w, r) return } template, err := template.ParseFiles(lp_layout, lp_header, lp_footer, lp_prideflag, fp) if err != nil { fmt.Printf("Error parsing template files: %s\n", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } err = template.ExecuteTemplate(w, "layout.html", data) if err != nil { fmt.Printf("Error executing template: %s\n", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } }) }