arimelody.me/global/global.go
2024-08-31 01:52:33 +01:00

103 lines
2.8 KiB
Go

package global
import (
"fmt"
"net/http"
"os"
"path/filepath"
"html/template"
"strconv"
"time"
)
var MimeTypes = map[string]string{
"css": "text/css; charset=utf-8",
"png": "image/png",
"jpg": "image/jpg",
"webp": "image/webp",
"html": "text/html",
"asc": "text/plain",
"pub": "text/plain",
"txt": "text/plain",
"js": "application/javascript",
}
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")
})
}
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)
}
fmt.Printf("[%s] %s %s - %d (%sms) (%s)\n",
after.Format(time.UnixDate),
r.Method,
r.URL.Path,
lrw.Code,
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
}
})
}