chizap/config.go

63 lines
1.5 KiB
Go

package chizap
import (
"net"
"net/http"
"go.uber.org/zap"
)
type Filter func(r *http.Request) bool
type AdditionalFieldExtractor func(r *http.Request) []zap.Field
type config struct {
filters []Filter
ipFn func(r *http.Request) string
additionalFieldExtractors []AdditionalFieldExtractor
}
type Option func(*config)
func newConfig(opts ...Option) *config {
cfg := &config{
ipFn: func(r *http.Request) string {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
},
}
for _, opt := range opts {
opt(cfg)
}
return cfg
}
// WithFilter adds a filter to the list of filters used by the middleware.
// If any filter indicates to exclude a request then the request will not be logged.
// All filters must allow a request to be logged.
// If no filters are provided, then all requests are logged.
func WithFilter(f Filter) Option {
return func(c *config) {
c.filters = append(c.filters, f)
}
}
// WithAdditionalFieldExtractor takes a function that will be called on every
// request and the returned fields will be added to the log entry.
func WithAdditionalFieldExtractor(extractor AdditionalFieldExtractor) Option {
return func(c *config) {
c.additionalFieldExtractors = append(c.additionalFieldExtractors, extractor)
}
}
// WithIPFn takes a function that will be called on every
// request and the returned ip will be added to the log entry.
// http.Request RemoteAddr is logged by default.
func WithIPFn(fn func(r *http.Request) string) Option {
return func(c *config) {
c.ipFn = fn
}
}