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]) })
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 {
panic(err)
}

View File

@ -67,8 +67,10 @@ func New() *kserver {
if err != nil {
panic(err)
}
k := &kserver{}
k.l = l
k := &kserver{
l: l,
nolog: func(r *http.Request) bool { return true },
}
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) {
ex := recover()
if ex != nil {
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 {
k.l.ErrorF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path}, rw.err)
} else {
k.l.InfoF(log.H{"Status": rw.StatueCode, "IP": GetIP(r), "Method": r.Method, "URL": r.URL.Path})
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 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, "Agent": r.Header.Get("User-Agent")})
}
}

View File

@ -9,6 +9,13 @@ import (
type kserver struct {
http.Server
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

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]) })
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 {
panic(err)
}