Source File
requestlog.go
Belonging Package
golang.org/x/pkgsite/internal/middleware
package middleware
import (
)
type LocalLogger struct{}
func ( LocalLogger) ( logging.Entry) {
var strings.Builder
if .HTTPRequest != nil {
.WriteString(strconv.Itoa(.HTTPRequest.Status) + " ")
if .HTTPRequest.Request != nil {
.WriteString(.HTTPRequest.Request.URL.Path + " ")
}
}
.WriteString(fmt.Sprint(.Payload))
log.Info(context.Background(), .String())
}
func ( Logger) Middleware {
return func( http.Handler) http.Handler {
return &handler{delegate: , logger: }
}
}
type handler struct {
delegate http.Handler
logger Logger
}
func ( *handler) ( http.ResponseWriter, *http.Request) {
:= time.Now()
:= .Header.Get("X-Cloud-Trace-Context")
:= logging.Info
if .Method == http.MethodGet && .URL.Path == "/healthz" {
= logging.Debug
}
.logger.Log(logging.Entry{
HTTPRequest: &logging.HTTPRequest{Request: },
Payload: map[string]string{
"requestType": "request start",
},
Severity: ,
Trace: ,
})
:= &responseWriter{ResponseWriter: }
.delegate.ServeHTTP(, .WithContext(log.NewContextWithTraceID(.Context(), )))
:=
= logging.Warning
} else if .status >= 500 {
= logging.Error
}
.logger.Log(logging.Entry{
HTTPRequest: &logging.HTTPRequest{
Request: ,
Status: translateStatus(.status),
Latency: time.Since(),
},
Payload: map[string]interface{}{
"requestType": "request end",
"isRobot": isRobot(.Header.Get("User-Agent")),
},
Severity: ,
Trace: ,
})
}
var browserAgentPrefixes = []string{
"MobileSafari/",
"Mozilla/",
"Opera/",
"Safari/",
}
func ( string) bool {
if strings.Contains(strings.ToLower(), "bot/") || strings.Contains(, "robot") {
return true
}
for , := range browserAgentPrefixes {
if strings.HasPrefix(, ) {
return false
}
}
return true
}
type responseWriter struct {
http.ResponseWriter
status int
}
func ( *responseWriter) ( int) {
.status =
.ResponseWriter.WriteHeader()
}
func ( int) int {
if == 0 {
return http.StatusOK
}
return
![]() |
The pages are generated with Golds v0.3.2-preview. (GOOS=darwin GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |