arimelody.me/global/global.go

72 lines
1.7 KiB
Go
Raw Normal View History

package global
import (
"fmt"
"net/http"
"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",
}
var LAST_MODIFIED = time.Now()
func IsModified(req *http.Request, last_modified time.Time) bool {
if len(req.Header["If-Modified-Since"]) == 0 || len(req.Header["If-Modified-Since"][0]) == 0 {
return true
}
request_time, err := time.Parse(http.TimeFormat, req.Header["If-Modified-Since"][0])
if err != nil {
return true
}
if request_time.Before(last_modified) {
return true
}
return false
}
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])
})
}