You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package builtin
import (
"fmt"
"time"
ctxpkg "github.com/noahlann/nnet/pkg/context"
routerpkg "github.com/noahlann/nnet/pkg/router"
)
// LoggingMiddleware 日志中间件
func LoggingMiddleware ( ) routerpkg . Handler {
return func ( ctx ctxpkg . Context ) error {
start := time . Now ( )
conn := ctx . Connection ( )
// 记录请求开始
req := ctx . Request ( )
var requestStr string
if req . Data ( ) != nil {
// 如果Data是字符串或字节, 直接使用
if dataBytes , ok := req . Data ( ) . ( [ ] byte ) ; ok {
requestStr = string ( dataBytes )
} else if dataStr , ok := req . Data ( ) . ( string ) ; ok {
requestStr = dataStr
} else {
// 否则使用DataBytes
requestStr = string ( req . DataBytes ( ) )
}
} else {
requestStr = string ( req . Raw ( ) )
}
fmt . Printf ( "[%s] %s -> %s: %s\n" ,
start . Format ( "2006-01-02 15:04:05" ) ,
conn . RemoteAddr ( ) ,
conn . LocalAddr ( ) ,
requestStr ,
)
// 执行下一个处理器
// 这里需要在实际的路由处理中调用下一个处理器
// 由于中间件链的设计, 这个会在Chain中处理
// 这里只是记录日志,不处理错误
// 记录请求结束
duration := time . Since ( start )
fmt . Printf ( "[%s] %s -> %s: OK (duration: %v)\n" ,
time . Now ( ) . Format ( "2006-01-02 15:04:05" ) ,
conn . RemoteAddr ( ) ,
conn . LocalAddr ( ) ,
duration ,
)
return nil
}
}