improved logging

This commit is contained in:
milarin 2023-02-10 12:48:42 +01:00
parent a1e1413919
commit e7c72eb51b
4 changed files with 49 additions and 9 deletions

11
go.mod
View File

@ -2,4 +2,13 @@ module git.milar.in/milarin/httpserver
go 1.19
require git.milar.in/milarin/adverr v1.1.0
require (
git.milar.in/milarin/adverr v1.1.0
github.com/fatih/color v1.14.1
)
require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
golang.org/x/sys v0.3.0 // indirect
)

10
go.sum
View File

@ -1,2 +1,12 @@
git.milar.in/milarin/adverr v1.1.0 h1:jD9WnOvs40lfMhvqQ7cllOaRJNBMWr1f07/s9jAadp0=
git.milar.in/milarin/adverr v1.1.0/go.mod h1:joU9sBb7ySyNv4SpTXB0Z4o1mjXsArBw4N27wjgzj9E=
github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w=
github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

29
logging.go Normal file
View File

@ -0,0 +1,29 @@
package main
import (
"log"
"net/http"
"github.com/fatih/color"
)
var MethodColors = map[string]*color.Color{
"GET": color.New(color.FgBlue),
"POST": color.New(color.FgGreen),
"PUT": color.New(color.FgYellow),
"DELETE": color.New(color.FgRed),
}
func MethodToString(method string) string {
if str, ok := MethodColors[method]; ok {
return str.Sprint(method)
}
return method
}
func LogHandler(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", MethodToString(r.Method), r.URL.String())
handler.ServeHTTP(w, r)
}
}

View File

@ -3,7 +3,6 @@ package main
import (
"flag"
"fmt"
"log"
"net/http"
"path/filepath"
@ -34,10 +33,3 @@ func main() {
adverr.Fatalln(err, 1)
}
}
func LogHandler(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL)
handler.ServeHTTP(w, r)
}
}