feat: add handle shorthand

master
Evan Chen 2021-11-04 02:09:00 +08:00
parent 894dbc1bbf
commit 49c5239928
4 changed files with 22 additions and 9 deletions

View File

@ -25,7 +25,7 @@ func main() {
mux.HandleFunc("/out", func(rw http.ResponseWriter, r *http.Request) { arr := []int{0, 1}; fmt.Print(arr[9]) }) mux.HandleFunc("/out", func(rw http.ResponseWriter, r *http.Request) { arr := []int{0, 1}; fmt.Print(arr[9]) })
log.Info("start") log.Info("start")
err := ksrv.New().Listen("0.0.0.0:8080").Serve() err := ksrv.New().Handle(mux).Listen("0.0.0.0:8080").Serve()
if err != nil { if err != nil {
panic(err) panic(err)
} }

View File

@ -67,8 +67,10 @@ func New() *kserver {
if err != nil { if err != nil {
panic(err) panic(err)
} }
k := &kserver{} k := &kserver{
k.l = l l: l,
nolog: func(r *http.Request) bool { return true },
}
return k return k
} }
@ -82,14 +84,18 @@ func (k *kserver) Middleware(next http.Handler) http.Handler {
) )
} }
func (k *kserver) SetNoLogCondition(nolog func(r *http.Request) bool) {
k.nolog = nolog
}
func (k *kserver) catch(rw *responseWriter, r *http.Request) { func (k *kserver) catch(rw *responseWriter, r *http.Request) {
ex := recover() ex := recover()
if ex != nil { if ex != nil {
Abort(rw, ex) Abort(rw, ex)
k.l.ErrorF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path}, ex) k.l.ErrorF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path, "Agent": r.Header.Get("User-Agent")}, ex)
} else if rw.StatueCode >= 500 { } else if rw.StatueCode >= 500 {
k.l.ErrorF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path}, rw.err) k.l.ErrorF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path, "Agent": r.Header.Get("User-Agent")}, rw.err)
} else { } else if k.nolog != nil && k.nolog(r) {
k.l.InfoF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path}) k.l.InfoF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path, "Agent": r.Header.Get("User-Agent")})
} }
} }

View File

@ -8,7 +8,14 @@ import (
type kserver struct { type kserver struct {
http.Server http.Server
l *log.Logger l *log.Logger
nolog func(r *http.Request) bool
}
// Listen to addr
func (s *kserver) Handle(h http.Handler) *kserver {
s.Handler = h
return s
} }
// Listen to addr // Listen to addr

View File

@ -18,7 +18,7 @@ func main() {
mux.HandleFunc("/out", func(rw http.ResponseWriter, r *http.Request) { arr := []int{0, 1}; fmt.Print(arr[9]) }) mux.HandleFunc("/out", func(rw http.ResponseWriter, r *http.Request) { arr := []int{0, 1}; fmt.Print(arr[9]) })
log.Info("start") log.Info("start")
err := ksrv.New().Listen("0.0.0.0:8080").Serve() err := ksrv.New().Handle(mux).Listen("0.0.0.0:8080").Serve()
if err != nil { if err != nil {
panic(err) panic(err)
} }