This commit is contained in:
Anya Tokugawa committed 2026-05-19 21:30:42 +09:00
commit fa6a4c650f
93 files changed
+6555

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
package middleware
import (
"log"
"net/http"
"time"
)
func Logging(
next http.Handler,
) http.Handler {
return http.HandlerFunc(
func(
w http.ResponseWriter,
r *http.Request,
) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf(
"%s %s %s",
r.Method,
r.URL.Path,
time.Since(start),
)
},
)
}
+53
View File
@@ -0,0 +1,53 @@
package middleware
import (
"net/http"
"strings"
)
func NormalizePath(
next http.Handler,
) http.Handler {
return http.HandlerFunc(
func(
w http.ResponseWriter,
r *http.Request,
) {
p := r.URL.Path
if p != "/" {
for strings.HasSuffix(
p,
"/",
) {
p = strings.TrimSuffix(
p,
"/",
)
}
if p == "" {
p = "/"
}
if p != r.URL.Path {
http.Redirect(
w,
r,
p,
http.StatusMovedPermanently,
)
return
}
}
next.ServeHTTP(w, r)
},
)
}
+38
View File
@@ -0,0 +1,38 @@
package middleware
import (
"log"
"net/http"
)
func Recovery(
next http.Handler,
) http.Handler {
return http.HandlerFunc(
func(
w http.ResponseWriter,
r *http.Request,
) {
defer func() {
if err := recover(); err != nil {
log.Printf(
"panic recovered: %v",
err,
)
http.Error(
w,
"internal server error",
500,
)
}
}()
next.ServeHTTP(w, r)
},
)
}
+43
View File
@@ -0,0 +1,43 @@
package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
)
type contextKey string
const RequestIDKey contextKey = "request_id"
func RequestID(
next http.Handler,
) http.Handler {
return http.HandlerFunc(
func(
w http.ResponseWriter,
r *http.Request,
) {
id := uuid.NewString()
ctx := context.WithValue(
r.Context(),
RequestIDKey,
id,
)
w.Header().Set(
"X-Request-ID",
id,
)
next.ServeHTTP(
w,
r.WithContext(ctx),
)
},
)
}